0% found this document useful (0 votes)
12 views110 pages

Introduction to Python Programming

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and mathematics. It features a simple syntax, is open-source, and supports multiple programming paradigms including procedural, object-oriented, and functional programming. Python's architecture involves interpreting code into bytecode, which is executed by the Python Virtual Machine, and it emphasizes the importance of indentation for code structure.

Uploaded by

alhudda1077
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views110 pages

Introduction to Python Programming

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and mathematics. It features a simple syntax, is open-source, and supports multiple programming paradigms including procedural, object-oriented, and functional programming. Python's architecture involves interpreting code into bytecode, which is executed by the Python Virtual Machine, and it emphasizes the importance of indentation for code structure.

Uploaded by

alhudda1077
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-1: INTRODUCTION

⚫Python is a popular programming language. It was


created by Guido van Rossum, and released in 1991.
⚫It is used for:
⚫web development (server-side),
⚫software development,
⚫Mathematics,etc.
FEATURES OF PYTHON
⚫ Easy to code: Python is a high-level programming language
⚫ Free and Open Source
⚫ Object-Oriented Language
⚫ GUI Programming Support
⚫ High-Level Language
⚫ Extensible
⚫ Python is Portable language
⚫ Python is Integrated language
Why Python?
⚫ Python works on different platforms (Windows, Mac,
Linux,etc).
⚫ Python has a simple syntax similar to the English language.
⚫ Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
⚫ Python runs on an interpreter system, meaning that code
can be executed as soon as it is written.
⚫ Python can be treated in a procedural way, an object-
oriented way or a functional way.
What can Python do?
⚫Python can be used on a server to create web
applications.
⚫Python can be used alongside software to create
workflows.
⚫Python can connect to database systems. It can also
read and modify files.
⚫Python can be used to handle big data and perform
complex mathematics.
Example
print("Hello, World!")
output:
Hello,World!
PYTHON ARCHITECTURE
⚫ Python is an object oriented programming language like
Java. Python is called an interpreted language.
⚫ Python doesn’t convert its code into machine code. It
actually converts it into something called byte code and this
byte code can’t be understood byCPU. Sowe need actually
an interpreter called the python virtual [Link] python
virtual machine executes the byte codes.
Python Architecture
Tasks of Python interpreter to execute
a Python program :
⚫ Step 1 :The interpreter reads a python code or [Link]
it verifies that the instruction is well formatted, i.e. it checks the
syntax of each line. If it encounters any error, it immediately
halts the translation and shows an error message.
⚫ Step 2 : If there is no error, then the interpreter translates it into
its equivalent form in intermediate language called “Byte code”.
⚫ Step 3 : Byte code is sent to the PythonVirtual
Machine(PVM).Here again the byte code is executed on PVM. If
an error occurs during this execution then the execution is halted
with an error message.
Python Indentation
⚫ Indentation refers to the spaces at the beginning of a code line.
⚫ Where in other programming languages the indentation in code is
for readability only, the indentation in Python is very important.
⚫ Python uses indentation to indicate a block of code.
⚫ Example:
⚫ if (5 > 2):
print("Five is greater than two!")
⚫ if 5 > 2:
print("Five is greater than two!")
⚫ Syntax Error:
Python Indentation
• The number of spaces is up to you as a programmer, but it
has to be at least one.

• Example
• if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
• Five is greater than two!
Five is greater than two!
Python Indentation
⚫ You have to use the same number of spaces in the same block of
code, otherwise Python will give you an error.
⚫ if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
⚫ Syntax Error
Python Variables
In Python, variables are created when you
assign a value to it.
x= 5
y = "Hello, Python!“

Python has no command for declaring a


variable.
Comments
Python has commenting capability for the
purpose of in-code documentation.

Comments start with a # , and Python will


render the rest of the line as a comment.

#This is a comment.
print("Hello, World!")
Exercise
⚫ Insert the missing part of the code below to output "Hello
World".
⚫ if 5 > 2:
if 5 > 2:
print("Five is greater than two!")

This is a comment
written in more that
just one line

Display the sum of 5 + 10, using two


variables: x and y.
Get the type of a variable
Youcan get the data type of avariable with
the type() function.
x= 5
y = “Abdi“
print(type(x))
print(type(y))

Output:
<class 'int'>
<class 'str'>
Case-Sensitive
Variable names are case-sensitive.
a=4
A= “Abdi“
NOTE:Awill not overwrite a.

Output:
4
Abdi
Python - Variable Names
⚫ Avariable can have ashort name (like x and y) or amore
descriptive name (age, carname, total_volume).
Rules for Python variables:
1. Avariable name must start with a letter or the underscore
character.
2. Avariable name cannot start with a number.
3. Avariable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ ).
4. Variable names are case-sensitive (age, Age and AGEare three
different variables).
Multi Words Variable Names
⚫ Variable names with more than one word can be difficult to read.
⚫ There are several techniques you can use to make them more
readable:
Camel Case:
⚫ Each word, except the first, starts with a capital.e.g.:
myVariableName = “Abdi" letter
Pascal Case:
⚫ Each word starts with a capital letter.
⚫ E.g.: MyVariableName = “Abdi“
Snake Case:
⚫ Each word is separated by an underscore character: e.g.:
my_variable_name = “Abdi"
Python Variables - Assign Multiple Values
Python allows you to assign values to multiple
variables in one line.
x, y, z = "Orange", "Banana", "Cherry“
print(x)
print(y)
print(z)

Output:
Orange
Banana
Cherry
One Value to Multiple Variables
you can assign the samevalue to multiple
variables in one line.
x = y = z = "Orange«
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list. Python
allows you extract the values into
variables. This is called unpacking.

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

Output:
Apple
Banana
cherry
Python - Output Variables
⚫ The Python ’print’statement is often used to output
variables.
⚫ To combine both text and a variable, Python uses
the + character.

⚫ x = "easy"
print("Python is " + x)

⚫ Output:
⚫ Python is easy

Python - Output Variables
Youcan also use the + character to add a variable to another variable.
• x = "Python is "
y = “easy"
z= x+ y
print(z)

• Output:
• Python is easy

• For numbers, the + character works as a mathematical operator.


• x= 5
y = 10
print(x + y)
If you try to combine a string and a number,
Python will give you an error.
x= 5
y = “Abdi“
print(x + y)

Output:
TypeError: unsupported operand type(s) for + :
'int' and 'str'
PYTHON DATATYPES
Built-in DataTypes
⚫ In programming, data type is an important concept.
⚫ Variables can store data of different types, and different types can
do different things.
⚫ Python has the following data types built-in by default, in these
categories.
⚫ TextType:str
⚫ NumericTypes:int, float, complex
⚫ SequenceTypes:list, tuple, range
⚫ MappingType: dictionary
⚫ SetTypes:set
⚫ BooleanType:bool
Setting the Data Type
In Python, the data type is set when you assign
a value to a variable.

Example DataType
x = "HelloWorld" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = {"name" : “Abdi", "age" : 36} Dict
x = {"apple", "banana", "cherry"} Set
x =True bool
Setting the Specific Data Type
If you want to specify the data type, you can
use the following constructor functions.
x = str("HelloWorld") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = dict(name="Abdi", age=36) dict
x = set(("apple", "banana", "cherry")) set
Python Numbers
There are three numeric types in Python:
⚫ int
⚫ float
⚫ complex
Variables of numeric types are created when you assign
a value to them.

Int: Int, or integer, is a whole number, positive or negative,


without decimals, of unlimited length.
x= 1
y = 35656222554887711
z = -3255522
Python Numbers
Float: Float, or "floating point number" is a number,
positive or negative, containing one or more
decimals.
x = 1.10
y = 1.0
z = -35.59

Complex: Complex numbers are written with a "j" as


the imaginary part.
x = 3+5j
y = 5j
z = -5j
Type Conversion
Youcan convert from one type to another with
the int(), float(), and complex() methods.
x = 1 # int
y = 2.8 # float
z = 1j # complex

convert from int to float:


a = float(x)

convert from float to int:


b = int(y)

convert from int to complex:


c = complex(x)
print(a) print(type(a))
print(b) print(type(b))
print(c) print(type(c))

Note:You cannot convert complex numbers into another number type.


Random Number
Python does not have a random() function to
make a random number, but Python has a built-in
module called random that can be used to make
random numbers.

Import the random module, and display a random


number between 1 and 9.

import random
print([Link](1, 10))
Python-Strings
⚫ Strings in python are surrounded by either single quotation
marks, or double quotation marks.
⚫ 'hello' is the same as "hello".

Assign String to aVariable:


a = "Hello“
print(a)
Strings are Arrays
⚫ Python does not have a character data type, a single character is
simply a string with a length of 1.
⚫ Square brackets can be used to access elements of the string.

⚫ a = "Hello,World!"
print(a[1])

⚫ Output:
⚫e
String Length
⚫ To get the length of a string, use the len() function.
⚫ The len() function returns the length of a string.

⚫ a = "Hello,World!"
print(len(a))

⚫ Output:
⚫ 13
Python - Slicing Strings
⚫ You can return a range of characters by using the slice syntax.
⚫ Specify the start index and the end index, separated by a colon, to
return a part of the string.

⚫ Get the characters from position 2 to position 5 (not included)


⚫ b = "Hello,World!"
print(b[2:5])

⚫ Output:
⚫ llo
Slice From the Start
Get the characters from the start to position 5 (not
included).
b = "Hello, World!"
print(b[:5])
Output: Hello

SliceTo the End


Get the characters from position 2, and all the way
to the end.
b = "Hello,World!"
print(b[2:])
Output: llo,World!
Negative Indexing
Use negative indexes to start the slice from the
end of the string.
⚫ From: "o" in "World!" (position -5)
⚫To, but not included: "d" in "World!" (position -2)
b = "Hello,World!"
print(b[-5:-2])
Output: orl
Python - Modify Strings
⚫ Python has a set of built-in methods that you can use on strings.
Upper Case: The upper() method returns the
string in upper case.
a = "Hello,World!"
print([Link]())
⚫ Output: HELLO,WORLD!

Lower Case: The lower() method returns the string in lower


Case.
print([Link]())
Output: hello, world!
Remove Whitespace
Whitespace is the space before and/or after the actual text, and
you want to remove this space.
The strip() method removes any whitespace from the beginning
or the end:
a = " Hello, World! “
print([Link]())
Output: "Hello,World!“

Replace String: The replace() method replaces a string with


another string.
a = "Hello,World!“
print([Link]("H", “K"))
Output: Kello, World!
Python - String Concatenation
To concatenate, or combine, two strings you can use the
+ operator.
Merge variable a with variable b into variable c.
a = "Hello“
b = "World“
c= a+ b
print(c)
Output: HelloWorld

To add a space between them, add ”“.


a = "Hello“
b = "World“
c= a+ " " + b
print(c)
Output: HelloWorld
String Format
As we learned in the PythonVariables chapter,
we cannot combine strings and numbers. But
we can combine strings and numbers by using
the format() method.
The format() method takes the passed
arguments, formats them, and places them in
the string where the placeholders {} are.
age = 36
txt = "My name isAmit, and I am {}“
print([Link](age))
Output: My name isAmit, and I am 36
Python Operators
Python divides the operators in the following
groups.
⚫ Arithmetic operators
⚫ Assignment operators
⚫ Comparison operators
⚫ Logical operators
⚫ Identity operators
⚫ Membership operators
⚫ Bitwise operators
Python Arithmetic Operators
Consider x=5 and y=3

OPERATOR NAME EXAMPLE Output

+ Addition x+y 8
- Subtraction x-y 2
* Multiply x*y 15
/ Divide x/y 1.67
% Modulus x%y 2
** Exponential X**y 125
// Floor division x//y 1
Python Assignment Operators
Consider X=5

OPERATOR EXAMPLE SAME AS


= X=5 X=5
+= X+=5 X=X+3
*= X*=5 X=X*3
/= X/=5 X=X/3
%= X%=5 X=X%3
//= X//=5 X=X//3
**= X**=5 X=X**3
&= X&=5 X=X&3
|= X|=5 X=X|3
Python Comparison Operators
Consider x=5 and y=3

OPERATOR NAME EXAMPLE Output


== Equal X==y False

!= Not Equal X!=y True

> Greater than x>y True

< Less than X<y False

>= Greater than or equal to x>=y True

<= Less than or equal to X<=y False


Python Logical Operators
Logical operators are used to combine
conditional statements. Consider x=3

OPERATOR DESCRIPTION EXAMPLE Output

Returns True if all of the x < 5 and x < 10 True


and
statements are true

Returns True if one of the x < 5 or x < 4 True


or
statements is true

Reverse the result, returns not(x < 5 and x < 10) False
not
False if the result is true
PYTHON-CONDITIONAL STATEMENTS
If Condition: Python supports the usual logical conditions.
⚫ Equals: a == b
⚫ Not Equals: a != b
⚫ Less than: a < b
⚫ Less than or equal to: a <= b
⚫ Greater than: a > b
⚫ Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly
in "if statements" and loops.
An"if statement" is written byusing the if keyword.
Example:
a= 3
b = 20
if b > a:
print("b is greater than a")
Example
⚫If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:print("b is greater than a") # you will get an error
Elif:
The elif keyword says "if the previous conditions were not true,
then try this condition“
Example:
a= 3
b= 3
if b > a:
print("b is greater than a")
elif a = = b:
print("a and b are equal")
Else: The else keyword catches anything which isn't caught by
the preceding conditions.
Example:
a = 40
b = 33
if b > a:
print("b is greater than a")
elif a = = b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
⚫ You can also have an else without the elif.
Example:
a = 40
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If: If you have only one statement to execute,


you can put it on the same line as the if statement.
Example: One line if statement.
a=40
B=33
if a > b: print("a is greater than b")
Short Hand If ... Else:
⚫ If you have only one statement to execute, one for if, and one
for else, you can put it all on the same line:
Example: One line if else statement.
a = 20
b = 30
print("A") if a > b else print("B")

• Youcan also have multiple else statements on the same line:


Example:
a = 330
b = 330
print("A") if a > b else print("=") if a = = b else print("B")
And:
⚫ The and keyword is a logical operator, and is used to combine
conditional statements.
Example: Test if a is greater than b,AND if c is greater than a.
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions areTrue")
Or: The or keyword is a logical operator, and is used to
combine conditional statements.
Example: Test if a is greater than b, OR if a is greater than c.
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions isTrue")
Nested If
Youcan have if statements inside if statements, this is
called nested if statements.
Example:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Python Loops
Python has two loop commands.
⚫ while loops
⚫ for loops
while Loop: With the while loop we can execute a set of
statements as long as a condition is true.
Example: Print i as long as i is less than 6.
i= 1
while i < 6:
print(i)
i += 1
The break Statement: With the break statement we can stop
the
loop even if the while condition is true.
Example: Exit the loop when i is 3.
i= 1
while i < 6:
print(i)
if i = = 3:
break
i += 1
The continue Statement: With the continue statement we
can stop the current iteration, and continue with the next.
Example: Continue to the next iteration if i is 3.
i= 0
while i < 6:
i += 1
if i = = 3:
continue
print(i)
The else Statement: With the else statement we can run a
block of code once when the condition no longer is true.
Example: Print a message once the condition is false:
i= 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Python For Loops
⚫ Afor loop is used for iterating over a sequence (that is either a list,
a tuple, a dictionary, a set, or a string).
⚫ With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
Example
⚫Print each language in a language list
languages=['english','hindi','german','french']
for language in languages:
print(language)
Output:
english
hindi
german
french
Looping Through a String
⚫ Even strings are iterable objects, they contain a sequence of
characters.
Example:
Loop through the letters in the word “python“
for x in 'python':
print(x)
Output:
p
y
t
h
o
n
The break Statement in for loop
⚫ With the break statement we can stop the loop before it has
looped through all the items.
Example
⚫Exit the loop when x is "banana“.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x = = "banana":
break
Output:
apple
banana
Example:
⚫ Exit the loop when x is "banana", but this time the break
comes before the print
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x = = "banana":
break
print(x)
Output:
apple
The continue Statement with for loop
⚫ With the continue statement we can stop the current
iteration of the loop, and continue with the next.
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x = = "banana":
continue
print(x)
Output:
apple
cherry
The range() Function
⚫ To loop through a set of code a specified number of times, we can
use the range() function,
⚫ The range() function returns a sequence of numbers, starting from
0 bydefault, and increments by 1 (by default), and ends at a
specified number.
Example:
for x in range(6):
print(x)
Output:
0
1
2
3
4
5
⚫ The range() function defaults to 0 as a starting value,
however it is possible to specify the starting value by adding a
parameter: range(2, 6), which means values from 2 to 6 (but
not including 6).
Example: Using the start parameter
for x in range(2, 6):
print(x)
Output:
2
3
4
5
⚫ The range() function defaults to increment the sequence by
1, however it is possible to specify the increment value by
adding a third parameter: range(2, 30, 3).
Example: Increment the sequence with 3
for x in range(2, 20, 3):
print(x)
Output:
2
5
8
11
14
17
Else in For Loop
⚫ The else keyword in a for loop specifies a block of code to be executed
when the loop is finished.
Example: Print all numbers from 0 to 5, and print a message
when the loop has ended.
for x in range(6):
print(x)
else:
print("loop finished!")
Output:
0
1
2
3
4
5
loop finished
⚫ Note:The else block will NOT be executed if the loop is
stopped by a break statement.
Example:
for x in range(6):
print(x)
if(x==3):
break
else:
print("loop finished!")
Output:
0
1
2
3
Nested for Loops
⚫ Anested loop is a loop inside a loop.
⚫ The "inner loop" will be executed one time for each
iteration of the "outer loop“.
Example: Print each color for every fruit.
color = ["red", "blue", "green"]
fruits = ["apple", "banana", "cherry"]
for x in color:
for y in fruits:
print(x, y)
The pass Statement
⚫ for loops cannot be empty, but if you for some reason have
afor loop with no content, put in the pass statement to avoid
getting an error.
Example:
for x in [0, 1, 2]:
pass
OUTPUT:
No output
Python Lists
⚫ Lists are used to store multiple items in a single variable.
⚫ Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 areTuple, Set, and Dictionary,
all with different qualities and usage.
⚫Lists are created using square brackets.
Example:
x=[1,2,3,4,5]
print(x)
OR
List=[‘amit’,’rajan’,’sumit’]
Print(List)
List Items
⚫ List items are ordered, changeable, and allow duplicate
values.
⚫ List items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered:
⚫ When we saythat lists are ordered, it means that the items
have a defined order, and that order will not change.
⚫ If you add new items to a list, the new items will be placed at
the end of the list.
Note: There are some list methods that will change the order,
but in general: the order of the items will not change.
Changeable:
⚫ The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created.
Allow Duplicates:
⚫ Since lists are indexed, lists can have items with the same value.
Example: Lists allow duplicate values
list = ["apple", "banana", "cherry", "apple", "cherry"]
print(list)

List Length:
⚫ To determine how many items a list has, use the len() function.
list = ["apple", "banana", "cherry"]
print(len(list))
List Items - Data Types
⚫ List items can be of any data type.
Example: String, int and boolean data types
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
• Alist can contain different data types.
Example: Alist with strings, integers and boolean values.
list1 = ["abc", 34,True, 40, "male"]
Python Collections (Arrays)
⚫ There are four collection data types in the Python
programming language:
⚫ List is acollection which is ordered and changeable. Allows
duplicate members.
⚫ Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
⚫ Set is a collection which is unordered and unindexed. No
duplicate members.
⚫ Dictionary is acollection which is unordered and
changeable. No duplicate members.
Python - Access List Items
⚫ List items are indexed and you can access them by referring
to the index number.
Example: Print the second item of the list:
list = ["apple", "banana", "cherry"]
print(list[1])
❑ Negative Indexing
❑ Range of Indexes
Check if Item Exists: To determine if a specified item is
present in a list use the in keyword.
Example: Check if "apple" is present in the list:
list = ["apple", "banana", "cherry"]
if "apple" in list:
print("Yes, 'apple' is in the list")
Python - Change List Items
⚫ To change the value of a specific item, refer to the index
number.
Example: Change the second item:
list = ["apple", "banana", "cherry"]
list[1] = "blackcurrant“
print(list)
Change a Range of Item Values
⚫ Tochange the value of items within aspecific range, define a
list with the new values, and refer to the range of index
numbers where you want to insert the new values:
Example: Change the values "banana" and "cherry" with
the values "blackcurrant" and "watermelon":
list =
["apple", "banana", "cherry", "orange", "kiwi", "mango"]
list[1:3] = ["blackcurrant", "watermelon"]
print(list)
Output:
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
⚫ If you insert moreitems than you replace, the new items will
be inserted where you specified, and the remaining items
will move accordingly:
Example: Change the second value by replacing it
with twonew values:
list = ["apple", "banana", "cherry"]
list[1:2] = ["blackcurrant", "watermelon"]
print(list)
Output:
['apple', 'blackcurrant', 'watermelon', 'cherry']
⚫ If you insert less items than you replace, the new items will
be inserted where you specified, and the remaining items
will move accordingly:
Example: Change the second and third value by replacing
it with onevalue:
list = ["apple", "banana", "cherry"]
list[1:3] = ["watermelon"]
print(list)
Output:
['apple', 'watermelon']
Insert Items
⚫ To insert a new list item, without replacing any of the
existing values, we can use the insert() method.
⚫ The insert() method inserts an item at the specified index:
Example: Insert "watermelon" as the third item:
list = ["apple", "banana", "cherry"]
[Link](2, "watermelon")
print(list)
OutPut:
['apple', 'banana', 'watermelon', 'cherry']
Append Items
⚫ To add an item to the end of the list, use
the append() method:
Example: Using the append() method to append an item:
list = ["apple", "banana", "cherry"]
[Link]("orange")
print(list)
OutPut: ['apple', 'banana', 'cherry', 'orange']
Extend List
⚫ To append elements from another list to the current list, use
the extend() method.
Example: Add the elements of tropical to thislist:
list1 = ["apple", "banana", "cherry"]
list2 = ["mango", "pineapple", "papaya"]
[Link](list2)
print(list1)
Output:
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
Add Any Iterable
⚫ The extend() method does not haveto append lists, you can
add any iterable object (tuples, sets, dictionaries etc.).
Example: Add elements of a tuple to a list:
list = ["apple", "banana", "cherry"]
tuple = ("kiwi", "orange")
[Link](tuple)
print(list)
OutPut:
['apple', 'banana', 'cherry', 'kiwi', 'orange']
Python - Remove List Items
Remove Specified Item
⚫The remove() method removes the specified item.
Example: Remove "banana":
list = ["apple", "banana", "cherry"]
[Link]("banana")
print(list)
Output: ['apple', 'cherry']
Remove Specified Index
The pop() method removes the specified index.
Example: Remove the second item:
list = ["apple", "banana", "cherry"]
[Link](1)
print(list)
Output: ["apple", "cherry"]
⚫ If you do not specify the index, the pop() method removes
the last item.
Example: Remove the last item:
list = ["apple", "banana", "cherry"]
[Link]()
print(list)
Output: ["apple", "banana""]
⚫The del keyword also removes the specified index:
Example: Remove the first item:
list = ["apple", "banana", "cherry"]
del list[0]
print(list)
Output: ["banana", "cherry"]
⚫ The del keyword can also delete the list completely.
Example: Delete the entire list:
list = ["apple", "banana", "cherry"]
del list
Output: NameError: name 'list' is not defined.
Clear the List
⚫ The clear() method empties the list.
⚫ The list still remains, but it has no content.
Example: Clear the list content:
list = ["apple", "banana", "cherry"]
[Link]()
print(list)
Output: []
Loop Through a List
⚫Youcan loop through the list items by using a for loop:
Example: Print all items in the list, one by one:
list = ["apple", "banana", "cherry"]
for x in list:
print(x)
Output:
Apple
Banana
Cherry
Loop Through the Index Numbers
⚫ Youcan also loop through the list items by referring to their
index number.
⚫ Use the range() and len() functions to create a suitable
iterable.
Example
⚫ Print all items by referring to their index number:
list = ["apple", "banana", "cherry"]
for i in range(len(list)):
print(list[i]
Using a While Loop
⚫ You can loop through the list items by using a while loop.
⚫ Use the len() function to determine the length of the list,
then start at 0 and loop your way through the list items by
refering to their indexes.
⚫ Remember to increase the index by 1 after each iteration.
Example: Print all items, using a while loop to go through all
the index numbers
list = ["apple", "banana", "cherry"]
i= 0
while i < len(list):
print(list[i])
i= i+ 1
List Comprehension
⚫ List comprehension offers a shorter syntax when you want to
create a new list based on the values of an existing list.
Example: Based on alist of fruits, you want anew list,
containing only the fruits with the letter "a" in the name.
Example:
⚫ fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
[Link](x)
print(newlist)
Output: ['apple', 'banana', 'mango']
⚫ With list comprehension you can do all that with only one
line of code:
Example:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Output: ['apple', 'banana', 'mango']

You can set the outcome to whatever you like.


fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = ['hello' for x in fruits]
print(newlist)
Output: ['hello', 'hello', 'hello', 'hello', 'hello']
Sort Descending
⚫ Tosort descending, use the keyword argument reverse =
True
Example: Sort the list descending:
list = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link](reverse = True)
print(list)
Output: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
Sort List Alphanumerically
⚫ List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
Example: Sort the list alphabetically:
list = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(list)
Output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
Example: Sort the list numerically:
list = [100, 50, 65, 82, 23]
[Link]()
print(list)
Output: [23, 50, 65, 82, 100]
Case Insensitive Sort
⚫ Bydefault the sort() method is case sensitive, resulting in all
capital letters being sorted before lower case letters:
Example: Case sensitive sorting can give an unexpected result:
list = ["banana", "Orange", "Kiwi", "cherry"]
[Link]()
print(list)
Output: ['Kiwi', 'Orange', 'banana', 'cherry']
Join Two Lists
⚫ There are several ways to join, or concatenate, two or more lists in
Python.
⚫One of the easiest ways are by using the + operator.
Example: Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output: ['a', 'b', 'c', 1, 2, 3]

Example: Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
[Link](list1)
print(list2)
List Methods
⚫ Python has a set of built-in methods that you can use on lists.
Method Description

append() Adds an element at the end of the list


clear() Removes all the elements from the list
copy() Returns a copy of the list
extend() Add the elements of a list (or any iterable), to the end of the
current list
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Tuple
⚫ Tuples are used to store multiple items in a single variable.
⚫ Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary,
all with different qualities and usage.
⚫ Atuple is a collection which is ordered and unchangeable.
⚫ Tuples are written with round brackets.

Tuple Items
⚫ Tuple items are ordered, unchangeable, and allow duplicate
values.
⚫ Tuple items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered
⚫ When we say that tuples are ordered, it means that the items
have a defined order, and that order will not change.
Unchangeable
⚫ Tuples are unchangeable, meaning that we cannot change,
add or remove items after the tuple has been created.
Allow Duplicates
⚫ Since tuple are indexed, tuples can haveitems with the same
value.
Tuple Length
⚫ To determine how many items a tuple has, use
the len() function
CreateTupleWith One Item
⚫ Tocreate a tuple with only one item, you have to add a
comma after the item, otherwise Python will not recognize it
as a tuple.
Example: One item tuple, remember the commma:
⚫ tuple = ("apple",)
print(type(tuple))

#NOT a tuple
tuple = ("apple")
print(type(stuple))
Output:
<class 'tuple'>
<class 'str'>
Tuple Items - Data Types
⚫ Tuple items can be of any data type.
Example: String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
⚫ Atuple can contain different data types:
Example
⚫ Atuple with strings, integers and boolean values:
tuple1 = ("abc", 34,True, 40, "male")
AccessTuple Items
⚫ Youcan access tuple items by referring to the index number,
inside square brackets.
Example: Print the second item in the tuple:
tuple = ("apple", "banana", "cherry")
print(tuple[1])
Negative Indexing
⚫ Negative indexing means start from the end.
⚫ -1 refers to the last item, -2 refers to the second last item
etc.
Example: Print the last item of the tuple:
⚫ tuple = ("apple", "banana", "cherry")
print(tuple[-1])
Output: cherry
Range of Indexes
⚫ Youcan specify a range of indexes by specifying where to
start and where to end the range.
⚫ When specifying a range, the return value will be a new
tuple with the specified items.
Example: Return the third, fourth, and fifth item:
tuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(tuple[2:5])
Output: ("cherry", "orange", "kiwi")
Example: This example returns the items from the beginning.
tuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(tuple[:4])
Output: ("apple", "banana", "cherry", "orange“)
Range of Negative Indexes
⚫ Specify negative indexes if you want to start the search from the
end of the tuple
Example: This example returns the items from index -4 (included)
to index -1 (excluded)
tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(tuple[-4:-1])
Output: ("orange", "kiwi", "melon“)
Check if Item Exists
⚫ To determine if a specified item is present in a tuple use
the in keyword:
Example: Check if "apple" is present in the tuple:
tuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
ChangeTupleValues
⚫ Once atuple is created, you cannot change its [Link]
are unchangeable, or immutable.
⚫ But you can convert the tuple into alist, change the list, and
convert the list back into a tuple.
Example: Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi“
x = tuple(y)
print(x)
Output: ("apple", "kiwi", "cherry")
Add Items
⚫ Once a tuple is created, you cannot add items to it.
Example: Youcannot add items to a tuple:
tuple = ("apple", "banana", "cherry")
[Link]("orange") # This will raise an error
print(tuple)
But you can convert the tuple into a list, add "orange", and
convert it back into a tuple.
Example:
tuple = ("apple", "banana", "cherry")
y = list(tuple)
[Link]("orange")
tuple = tuple(y)
Output: ('apple', 'banana', 'cherry', 'orange')
Unpacking aTuple
⚫ When we create a tuple, we normally assign values to [Link] is
called "packing" a tuple
Packing a tuple:
⚫ fruits = ("apple", "banana", "cherry")
⚫ But, in Python, we are also allowed to extract the values back into
variables. This is called "unpacking“.
Example: Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(a,b,c) = fruits
print(a)
print(b)
print(c)
Output:
apple
banana
cherry
Example: Assign the rest of the values as a list called "red“.
⚫fruits = ("apple", "banana", "cherry", "strawberry",
"raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
Output:
apple
banana
['cherry', 'strawberry', 'raspberry']
If the * is added to another variable name than the last, Python
will assign values to the variable until the number of values left
matches the number of variables left.
LoopThrough aTuple:
Looping can be done same as list. Byfor/range/while loop.

Join Two Tuples


⚫ To join two or more tuples you can use the + operator:
Example: Join two tuples.
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output: ('a', 'b', 'c', 1, 2, 3)
MultiplyTuples
⚫ If you want to multiply the content of a tuple a given number
of times, you can use the * operator:
Example: Multiply the fruits tuple by 2:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
Tuple Methods

⚫ Python has two built-in methods that you can use on tuples.

Method Description
count() Returns the number of times aspecified value
occurs in a tuple
index() Searches the tuple for a specified value and
returns the position of where it was
found

You might also like