FUNDAMENTALS OF
PYTHON
Surbhi Chhabra
Assistant Professor, JKLU, Jaipur
OVERVIEW
▪ We will explore :
• Python Lists
• Python List Methods
• Python Tuples
P R A C T I C E , P R A C T I C E , PRACTICE
The best way to improve your programming and problem
skills is to practice!
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 2
PYTHON LIST
• Python’s built-in list type is also a collection type. A list is an object that
contains multiple data items.
• Each item that is stored in a list is called an element. Here is a statement that
creates a list :
info = [‘Alice', 27, 1550.87] # The items that are enclosed in square brackets and
separated by commas are the list elements.
• In fact, like strings, lists are a sequence type and are an iterable type. However,
a list differs from a string in two fundamental ways:
1. A list can contain a sequence of elements of any type, even different typed elements
mixed together in the same list.
2. A list is a mutable type. This means that, unlike a string object, a list object can be
changed after it is initially created.
• myList = [1, 'a', 3.14159, True]
• print(len(myList) 4
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 3
EXAMPLES OF PYTHON LIST
• A_list = [1,2,'a',3.14159]
• Week_days_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday’]
• list_of_lists = [ [1,2,3], ['a','b','c’]] # The list_of_lists is a list of only two elements. A list can
be a sequence of any typed element—even another list!
print(list_of_lists[0][2]) 3
print(list_of_lists[1][1]) b
• X= [ ] # The special list with no elements, designated as [ ], is called the empty list. Like
other “empty” elements, it is equivalent to a False value in Python.
• list2 = list() #empty list
• list_from_collection = list('Hello’) # The list_from_collection is a list built using the
constructor list. The resulting list is ['H', 'e', 'l', 'l', 'o'], containing five elements, each a
single character string. This constructor takes a single argument and that argument must
an iterable. The list constructor takes each element of the argument iterable and adds that
element to the new list.
• numbers = list(range(5)) # The list [0, 1, 2, 3, 4] is assigned to the numbers variable.
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 4
LIST INDEXING AND SLICING
• mylist = [1,'a',3.14159,True]
• mylist[1] a
• mylist[-1] True
• mylist[:] [1, 'a', 3.14159, True]
• mylist[:3:2] [1, 3.14159]
• mylist[::2] [1, 3.14159]
• mylist[2:] [3.14159, True]
• mylist[:3] [1, 'a', 3.14159]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 5
LIST : THE REPETITION OPERATOR
Here is the general format:
list * n
In the general format, list is a list, and n is the number of copies to make.
>>> numbers = [0] * 5
>>> print(numbers) [0, 0, 0, 0, 0]
>>> numbers = [1, 2, 3] * 3
>>> print(numbers) [1, 2, 3, 1, 2, 3, 1, 2, 3]
CONCATENATING LISTS
• To concatenate means to join two things together. You can use the + operator to
concatenate two lists. Here is an example:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
list3 = list1 + list2 [1, 2, 3, 4, 5, 6, 7, 8] #Concatenating two lists
list1 += list2 [1, 2, 3, 4, 5, 6, 7, 8] #Appending with +=
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 6
LIST ARE MUTABLE
Lists in Python are mutable, which means their elements can be changed. Contrast
this with strings that are immutable, which means that they cannot be updated in
place. The following code shows an example:
• numbers = [1, 2, 3, 4, 5]
• print(numbers) [1, 2, 3, 4, 5]
• numbers[0] = 99
• print(numbers) [99, 2, 3, 4, 5]
COMPARISON OPERATORS
a = [1, 2, 3]
b = [1, 2, 3]
c = [1, 2, 3, 4]
a == b # True: corresponding elements in both are equal
a == c # False: a and c have different elements and lengths
a < c # True: a has fewer elements than c
c >= b # True: elements 0-2 are equal but c has more elements
5 in c #False
[1,2,'one','two'] < [3,4,5,6] # no error , difference occurs on same type 1 and 3 (True)
[1,2,'one','two’] < [1,2,5,6] # error , comparison of 5 and 'one’ ( TypeError:
unorderable types: str() < int() )
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 7
LIST ARE MUTABLE
Mutability makes lists powerful; but reckless exercise of power always results in
instability as is demonstrated by this notorious example:
1. list1 = [1, 2, 3]
2. list2 = list1
3. list2[0] = 100
4. print(list1)
5. print(list2)
Both give the same output even though we are only modifying list2 in-place!
[100, 2, 3]
[100, 2, 3]
• To understand this, we will take the help of a built-in function called id.
• Every object in Python has a unique identity: if x is an object, then id(x) returns this
object's identity.
• From the Python documentation, "this is guaranteed to be unique among
simultaneously existing objects". In the implementation of the Python that we use,
this unique id is nothing but the object's memory address.
• In line-2, we are not creating a new object. We are merely creating another name
for the same object. (Just like we have name and nickname both)
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 8
LIST ARE MUTABLE
To see if two Python names point to the same object, we can use the is keyword:
list1 = [1, 2, 3]
list2 = list1
list2[0] = 100
print(list1 is list2) #True
Now consider another scenario:
1. list1 = [1, 2, 3]
2. list2 = [1, 2, 3]
3. print(list1 == list2) #True
4. print(list1 is list2) #False
• This is because equality and identity are two different things.
• In the code, line-3 checks for equality of two lists, line-4 checks if the two lists point
to the same object.
• list1 and list2 point to two different objects and consequently have different
identities. But, they store the same sequence of items and are hence equal.
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 9
LIST ARE MUTABLE
How do we create a copy of a list so that updating one doesn't end up changing both?
Python provides three ways to do this:
1. list1 = [1, 2, 3]
2. list2 = list(list1)
3. list3 = list1[:]
4. list4 = [Link]()
5. list2[0] = 100
6. list3[0] = 200
7. list4[0] = 300
8. print(list1, list2, list3, list4) #[1, 2, 3] [100, 2, 3] [200, 2, 3] [300, 2, 3]
9. print(list1 is not list2, list1 is not list3, list1 is not list4) #True, True, True
• In line-2, we pass list1 as an argument to the list function which returns a new list
object with the same sequence of elements as list1.
• In line-3, we are slicing the list. Slicing a list results in a new list object. As no start
or stop values are mentioned, they are going to default to 0 and len(list1)
respectively. So, the entire list is returned. However, it is a brand new object.
• In line-4, we use a method call copy that is defined for the list object.
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 10
CLASS QUIZ
• my_list = [True, 2, 'a', 'z’]
• my_list[-1] = 7 # change the last element [True, 2, 'a', 7]
• my_list[:2] = [27] # change the first two elements to one element [27, 'a', 7]
• my_list[:] = [1,2,3,4] # change the whole list [1, 2, 3, 4]
• my_list[2:] = 'abc' # change the last two elements [1, 2, 'a', 'b', 'c']
• my_list[:2]=15 # only an iterable Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
• numbers = [2, 3, 5, 7, 11, 13, 17, 19]
print(numbers[2:6]) #[5, 7, 11, 13] #Specifying a Slice with Starting and Ending Indices
print(numbers[:6]) #[2, 3, 5, 7, 11, 13] #Specifying a Slice with Only an Ending Index
print(numbers[6:]) #[17,19] #Specifying a Slice with Only an Starting Index
print(numbers[:]) #[2, 3, 5, 7, 11, 13, 17, 19] #Specifying a Slice with no Index
print(numbers[::2]) #[2, 5, 11, 17] #Slicing with Steps
print(numbers[-1:-9:-1]) #[19, 17, 13, 11, 7, 5, 3, 2] #Slicing with Negative Index and Steps
numbers = [2, 3, 5, 7, 11, 13, 17, 19]
numbers[0:3] = ['two', 'three', 'five’]
print(numbers) #['two', 'three', 'five', 7, 11, 13, 17, 19]
numbers = [2, 3, 5, 7, 11, 13, 17, 19]
numbers[0:3] = [ ]
print(numbers) #[7, 11, 13, 17, 19]
numbers = [2, 3, 5, 7, 11, 13, 17, 19]
numbers[::2] = [100, 100, 100, 100]
print(numbers) #[100, 3, 100, 7, 100, 13, 100, 19]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 11
LIST ITERATION
WE CAN ITERATE THROUGH ALL THE ELEMENTS OF A LIST, IN ORDER, USING THE FOR
OPERATOR.
# Method 1
my_list = [1,3,4,8]
for element in my_list: # iterate through list elements
print(element ,end=' ') # prints on one line 1 3 4 8
# Method 2 : Using a for Loop to Iterate by Index Over a List
names = ['Jenny', 'Kelly', 'Chlor', 'Aubrey']
for index in range(len(names)):
print(names[index])
As the for loop iterates, the index variable will be assigned the values 0, 1, 2, and 3.
The code will display the following:
Jenny
Kelly
Chlor
Aubrey
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 12
FINDING ITEMS IN LISTS WITH THE IN AND NOT IN OPERATORS
• In Python, you can use the in operator to determine whether an item is contained in
a list. Here is the general format of an expression written with the in operator to
search for an item in a list:
item in list
# Create a list of product numbers.
prod_nums = ['V475', 'F987', 'Q143', 'R688']
# Get a product number to search for.
search = input('Enter a product number:’)
# Determine whether the product number is in the list.
if search in prod_nums:
print(f'{search} was found in the list.')
else:
print(f'{search} was not found in the list.’)
# You can use the not in operator to determine whether an item is not in a list.
if search not in prod_nums:
print(f'{search} was not found in the list.’)
else:
print(f'{search} was found in the list.')
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 13
LIST METHODS
Non Modifying Methods
These methods do not change the list, but they return a value as a result of their
processing. They are:
• index(x): Returns the index of the first element in the list whose value is equal to x.
Python throws an error if there is no such value in the list.
• count(x): Returns the number of times x appears in the list. Returns 0 if x does not
appear in the list.
• len(): Returns the number of elements in the list.
• slice: You can use slicing to create a new list that contains a portion of the original
list without modifying it.
my_list = [1, 2, 3, 4, 5]
sub_list = my_list[1:4] # Returns [2, 3, 4], original list is unchanged
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 14
LIST METHODS
Methods which modify the List
append( ): Appends an element to the end of the list. The length of the list is
increased by one.
• a = [1, 12, 5, 8]
• print(a) [1, 12, 5, 8]
• [Link](17) # append to the end
• print(a) [1, 12, 5, 8, 17]
• [Link]([40,50,60]) # append a list rather than simply one item
• print(a) [1, 12, 5, 8, 17, [40, 50, 60]]
• b = [20, 2]
• [Link](b) # append another list's elements to end of a
• print(a) [1, 12, 5, 8, 17, [40, 50, 60], 20, 2]
extend( ): Requires a collection C as an argument. The list is extended by
adding each individual element of the another list to the end of the list.
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 15
LIST METHODS
insert(index, item): Inserts item into the list at the specified index.
• When an item is inserted into a list, the list is expanded in size to
accommodate the new item.
• The item that was previously at the specified index, and all the items after
it, are shifted by one position toward the end of the list.
• No exceptions will occur if you specify an invalid index. If you specify an
index beyond the end of the list, the item will be added to the end of the
list.
• If you use a negative index that specifies an invalid position, the item will
be inserted at the beginning of the list.
• insert is most useful when an element needs to be inserted at the
beginning of a list. Inserting an element at the end can be done using
append.
• a= [1, 12, 5, 8, 17, [40, 50, 60], 20, 2]
• [Link](3,30) # insert 30 at position 3
• print(a) [1, 12, 5, 30, 8, 17, [40, 50, 60], 20, 2]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 16
LIST METHODS
pop(): Removes the element at the end of the list and return that element. If no
argument is provided to pop, index defaults to -1.
If an index is specified, pop() removes the element at that position and returns
that item.
The list is shortened by one element.
a= [1, 12, 5, 30, 17, [40, 50, 60], 20, 2]
print(a) [1, 12, 5, 30, 17, [40, 50, 60], 20, 2]
[Link]( ) # pop last element off a list , and return it
print(a) [1, 12, 5, 30, 17, [40, 50, 60], 20]
B=[Link](3) # pop the element at the index 3
print(a) [1, 12, 5, 17, [40, 50, 60], 20]
print(B) 30
remove(x): Removes the first element from the list whose value is x. An error
results, if there is no such item. The length of the list is decreased by one if
successful.
a= [1, 5, 12, 5, 8, 17, [40, 50, 60], 20, 2]
[Link](8)
print(a) [1, 5, 12, 5, 17, [40, 50, 60], 20, 2]
[Link](5)
print(a) [1, 12, 5, 17, [40, 50, 60], 20, 2]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 17
LIST METHODS
sort(): Sorts the elements/items of the list, so they appear in ascending order
(from the lowest value to the highest value).
Note: If sorting a list of lists, only the first element in each list is considered in
the comparison operations. Only the order of the list elements is modified
(unless already sorted).
a= [1, 5, 12, 5, 8, 17, 20, 2]
[Link]()
print(a) [1, 2, 5, 5, 8, 12, 17, 20]
b=[[5,2,3,0,9,1],[4,5,3]]
[Link]()
print(b) [[4, 5, 3], [5, 2, 3, 0, 9, 1]]
reverse(): Reverses the elements of the list, in place. Only the order of the list
elements is modified.
a= [1, 5, 12, 5, 8, 17, 20, 2]
[Link]()
print(a) [2, 20, 17, 8, 5, 12, 5, 1]
b=[[5,2,3,0,9,1],[4,5,3]]
[Link]()
print(b) [[4, 5, 3], [5, 2, 3, 0, 9, 1]]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 18
LIST METHODS
copy(): The copy() method returns a copy of the specified list.
clear(): The clear() method removes all the elements from a list.
• a= [1, 5, 12, 5, 8, 17, 20, 2]
• b=[[5,2,3,0,9,1],[4,5,3]]
• c= [Link]()
• [Link]()
• print(a) [1, 5, 12, 5, 8, 17, 20, 2]
• print(c) [1, 5, 12, 5, 8, 17, 20, 2]
• print(b) [ ]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 19
The del Statement
The remove method removes a specific item from a list, if that item is in the list. The del statement remove
an element from a specific index, regardless of the item that is stored at that index.
my_list = [1, 2, 3, 4, 5]
print('Before deletion:', my_list) #Before deletion: [1, 2, 3, 4, 5]
del my_list[2]
print('After deletion:', my_list) #After deletion: [1, 2,4, 5]
my_list.remove(2)
print(my_list) [1,4, 5]
del my_list[:] []
my_list = [1, 2, 3, 4, 5]
del my_list[0:2]
print(my_list) #[3,4,5]
my_list = [1, 2, 3, 4, 5]
del my_list[::2]
print(my_list) #[2,4]
The min and max Functions
Python has two built-in functions named min and max that work with sequences.
• The min function accepts a sequence, such as a list, as an argument and returns the item that has the
lowest value in the sequence.
• The max function accepts a sequence, such as a list, as an argument and returns the item that has the
highest value in the sequence.
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The lowest value is', min(my_list)) The lowest value is 2
print('The highest value is', max(my_list)) The highest value is 50
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 20
LIST COMPREHENSION
A list comprehension is a concise expression that creates a new list by iterating over the
elements of an existing list. Examples are:
list1 = [1, 2, 3, 4]
list2 = []
for item in list1:
[Link](item**2)
print(list2) [1,4,9,16]
list2=[item**2 for item in list1] #[1,4,9,16]
str_list = ['Winken', 'Blinken', 'Nod']
len_list = []
for s in str_list:
len_list.append(len(s)) #len_list = [len(s) for s in str_list]
print(len_list) [6,7,3]
len_list=[len(s) for s in str_list]
list1 = [1, 12, 2, 20, 3, 15, 4]
list2 = []
for n in list1:
if n < 10:
[Link](n)
print(list2) [1,2,3,4]
list2=[n for n in list1 if n<10]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 21
TWO DIMENSIONAL LIST : NESTED LIST : MATRICES
A two-dimensional list is a list that has other lists as its elements (nested lists).
Matrices are 2D objects. We can represent them as nested lists.
list1 = [[‘a', ‘b'], [‘x', ‘y'], [‘p', ‘q']]
print(list1) [[‘a', ‘b'], [‘x', ‘y'], [‘p', ‘q']]
print(list1[0]) [‘a', ‘b']
print(list1[1]) [‘x', ‘y']
print(list1[2]) [‘p', ‘q']
Column 0 Column 1
Row 0 a b
Row 1 x y
Row 2 p q
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 22
TWO DIMENSIONAL LIST : NESTED LIST : MATRICES
mat = [ ]
for i in range(3):
[Link]([ ]) # we are appending an empty list
for _ in range(3):
mat[i].append(0)
print(mat)
mat = [[0 for _ in range(3)] for i in range(3)]
print(mat)
This gives the following output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
We have used _ as a loop variable. The inner-loop variable is insignificant and
never gets used anywhere. As a convention, we use the _ to represent such
variables whose sole purpose is to uphold the syntax of the language.
Column 0 Column 1 Column 2
Row 0 0 0 0
Row 1 0 0 0
Row 2 0 0 0
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 23
NESTED LIST
Access Nested List Items by Index: Multiple indexes can retrieve specific
items in a nested list. An example for the same is given below.
# creating a nested list
Nested_List = [10, 20, 30,['a', 'b', 'c'], 50]
# accessing the sublist by using the indexing method
Sub_List = Nested_List[3]
# accessing the second element of the sublist
data = Nested_List[3][1]
print("List inside the nested list: ", Sub_List) ['a', 'b', 'c']
print("Second element of the sublist: ", data) b
Add Items to a Nested List
Nested_list = [1, [2, 3], 4]
Nested_list[1].append(5)
print(Nested_list) [1,[2,3,5],4]
Nested_list[1].insert(1,5)
print(Nested_list) [1,[2,5,3,5],4]
Nested_list[1].extend([5,6,7])
print(Nested_list) [1,[2,5,3,5,5,6,7],4]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 24
NESTED LIST
Change Nested List Item Value:
Nested_list = [1, [2, 3], 4]
# changing that particular sublist index value
Nested_list[1][1] = 5
print(Nested_list) [1,[2,5],4]
Remove Items from a Nested List
Nested_list = [1, [2, 3], 4]
# Removing 3 from the sublist using pop() method
removed_item = Nested_list[1].pop(1)
print(Nested_list) [1,[2],4]
#Removed item
print(removed_item) 3
Nested_list = [1, [2, 3], 4]
del Nested_list[1][1]
print(Nested_list) [1, [2], 4]
Nested_list = [1, [2, 3], 4]
Nested_list[1].remove(3)
print(Nested_list) [1, [2], 4]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 25
NESTED LIST
Iterate Through a Nested List:
# Creating Nested List
Nested_list = [[1,2,3],[4,5,6,7],[8,9,10]]
#iterating over the nested list to access sublists
for sublist in Nested_list:
#iterating over the sublist to access items
for item in sublist:
print(item, end=‘ ‘) 1 2 3 4 5 6 7 8 9 10
Using Nested for Loops:
Nested_list = [[1,2,3,4,5], [6,7,8], [9, 10]]
flatttened_list = []
for sublist in Nested_list:
for item in sublist:
flattened_list.append(item)
print(flattened_list) [1,2,3,4,5,6,7,8,9,10]
Using List Comprehension:
Nested_list = [[1,2,3,4,5], [6,7,8], [9, 10]]
flattend_list = [item for sublist in Nested_list for item in sublist]
print(flattened_list) [1,2,3,4,5,6,7,8,9,10]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 26
SHALLOW AND DEEP COPY
Consider the following code:
mat1 = [[1, 2], [3, 4]]
mat2 = mat1
[Link]([5, 6])
print(mat1)
print(mat2)
print(mat1 is mat2)
Lists are mutable. mat2 is just an another name for mat1 and both point to the
same object. Modifying any one of them will modify both. We also saw three
different methods to copy lists so that modifying one doesn't modify the other.
Let us try one of them:
mat1 = [[1, 2], [3, 4]]
mat2 = [Link]()
[Link]([5, 6])
print(mat1) #[[1, 2], [3, 4]]
print(mat2) #[[1, 2], [3, 4], [5,6]]
print(mat1 is mat2) #False
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 27
SHALLOW AND DEEP COPY
Suppose we have:
mat1 = [[1, 2], [3, 4]]
mat2 = [Link]()
mat2[0][0] = 100
print(mat1) #[[100, 2], [3, 4]]
print(mat2) #[[100, 2], [3, 4]]
mat1 has also changed! Wasn't copy supposed to get rid of this difficulty?
We have a mutable object inside another mutable object. In such a case copy just does a shallow copy;
only a new outer-list object is produced. This means that the inner lists in mat1 and mat2 are still the
same objects:
print(mat1[0] is mat2[0]) #True
print(mat1[1] is mat2[1]) #True
In order to make a copy where both the inner and outer lists are new objects, we turn to deepcopy:
from copy import deepcopy
mat1 = [[1, 2], [3, 4]]
mat2 = deepcopy(mat1)
mat2[0][0] = 100
print(mat1) #[[1, 2], [3, 4]]
print(mat2) #[[100, 2], [3, 4]]
print(mat1 is not mat2) #True
print(mat1[0] is not mat2[0]) #True
print(mat1[1] is not mat2[1]) #True
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 28
TUPLES
• A tuple is a sequence, very much like a list (immutable lists).
• The primary difference between tuples and lists is that tuples are immutable.
That means once a tuple is created, it cannot be changed (cannot be updated
in-place).
• A tuple shares all the characteristics of a list except those that violate
immutability. That is, any function or method that can change a list is not
available for tuples.
• Because it is immutable, a tuple has some similarity to a string. However, as
with its cousin the list, a tuple can contain elements of any type.
• When you create a tuple, you enclose its elements in a set of parentheses,
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple) (1, 2, 3, 4, 5)
family = ('father', 'mother', 'child')
print(type(family)) <class 'tuple'>
print(isinstance(family, tuple)) True
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 29
TUPLES
• Creating Tuples: To create an empty tuple, use empty parentheses:
• When you output a tuple, Python always displays its contents in parentheses.
student_tuple = () #empty tuple
print(student_tuple) ()
print(len(student_tuple)) 0
another_student_tuple = ('Mary', 'Red', 3.3)
print(another_student_tuple) ('Mary', 'Red', 3.3)
a_singleton_tuple = ('red',) # note the comma
print(a_singleton_tuple) (‘red’,)
• It is important to note that the comma, not the parentheses, is the operator that creates the tuple. The
inclusion of the comma indicates that the parentheses are being used as part of tuple creation, not
grouping.
print((10,12)) # Python creates a tuple
tup = 2,3 # assigning a tuple to a variable
print(tup) (2,3)
a=(1) # not a tuple , a grouping
print(a) 1
a=(1,) # comma makes it a tuple
print(a) (1,)
x,y = 'a',3.14159 # multiple assignment from it
print(x) a
print(y) 3.14159
c=x,y # create a tuple
print(c) (‘a’, 3.14159)
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 30
TUPLES
Tuples support the following:
• Subscript indexing (for retrieving element values only)
• Operators such as + (concatenate) and * (repeat) work as before.
• Slicing also works as before.
• Membership (in) and for iteration also work on tuples.
• len, min, max, greater-than (>), less-than (<), sum, and others work the same
way. In particular, any comparison operation has the same restrictions for
mixed types.
• Operations that change lists are not available for tuples. For example, append,
extend, insert, remove, pop, reverse, and sort do not work on tuples.
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 31
TUPLES
• my_tuple = 1,2,3,4,5
• print(my_tuple) #(1, 2, 3, 4, 5)
• print(my_tuple + my_tuple) # concatenation ( addition ) #(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
• print(my_tuple * 3) # multiplication #(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
• print(my_tuple[1]) # indexing #2
• print(my_tuple[:3]) # slicing #(1, 2, 3)
• print(my_tuple[1:3]) #(2, 3)
• print(my_tuple[-1]) #5
• print(2 in my_tuple) # membership (in) #True
• print(10 in my_tuple) #False
• for x in my_tuple: # for
• print(x,end=' ') # 1 2 3 4 5
• print(len(my_tuple)) # length #5
• print(min(my_tuple)) # min and max #1
• print(max(my_tuple)) #5
• print(sum(my_tuple)) #15
• print((1,2,3) > (3,2,1)) #False
• tuple1 = (10, 20, 30)
• tuple2 = tuple1
• tuple1 += (40, 50) #addings items to a tuple
• print(tuple1) #(10, 20, 30, 40, 50)
• print(tuple2) #(10, 20, 30)
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 32
CONVERTING BETWEEN LIST AND TUPLES
We can use the built-in list() function to convert a tuple to a list, and the built-in tuple()
function to convert a list to a tuple.
number_tuple = (1, 2, 3)
number_list = list(number_tuple)
print(number_list) #[1, 2, 3]
str_list = ['one', 'two', 'three']
str_tuple = tuple(str_list)
print(str_tuple) #('one', 'two', 'three’)
Appending Tuples to Lists: We can use += to append a tuple to a list:
numbers = [1, 2, 3, 4, 5]
numbers += (6, 7)
print(numbers) #[1, 2, 3, 4, 5, 6, 7]
Tuples May Contain Mutable Objects:
Let’s create a student_tuple with a first name, last name and list of grades:
student_tuple = ('Ram', 'Sharma', [98, 75, 87])
student_tuple[2][1] = 85 #Even though the tuple is immutable, its list element is mutable
print(student_tuple) #('Ram', 'Sharma', [98, 85, 87])
a = ((1, 2, 3), (4, 5, 6)) #Tuples can be nested:
print(a[0][2]) #3
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 33
PACKING AND UNPACKING
T = 1, 2, 3
print(T)
print(isinstance(T, tuple))
T is the tuple (1, 2, 3). This is called tuple packing. The values 1, 2 and 3 are packed into a tuple. The
reverse operation is called sequence unpacking:
x, y, z = T
print(x, y, z) #1 2 3
Here, the tuple T is unpacked into the corresponding variables x, y and z. This is the principle behind
multiple assignment. Multiple assignment is a combination of tuple packing and sequence unpacking.
p1, p2, p3, p4 = 'good' # string
num1, num2, num3 = [1, 2, 3] # list
b1, b2 = (True, False) # tuple
x, y, z = range(3) # range
print(p1, p2, p3, p4 ) #g o o d
print(num1,num2,num3) #1 2 3
print(b1,b2) #True False
print(x,y,z) #0 1 2
Swapping Values Via Packing and Unpacking: We can swap two variables’ values using sequence
packing and unpacking:
number1 = 99
number2 = 22
number1, number2 = (number2, number1)
print(f'number1 = {number1}; number2 = {number2}') #number1 = 22; number2 = 99
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 34
PACKING AND UNPACKING
Tuple Unpacking Using The *(Asterisk) Operator:
If we have fewer variables than the number of elements in the tuple, we can use the * operator for tuple
unpacking in Python. The values will be assigned to the variable as a list:
myTuple=(1,12,11,14,123,32,76,114,56)
print("The tuple is:",myTuple) #The tuple is: (1, 12, 11, 14, 123, 32, 76, 114, 56)
a,b,c,*d=myTuple
print("The variables are:",a,b,c,d) #The variables are: 1 12 11 [14, 123, 32, 76, 114, 56]
In the above example, there are nine elements in the tuple. On the contrary, we have only four variables. You
can observe that the fourth variable d in the code uses the * operator. Hence, first three elements of the
tuple are assigned to the variables a, b, and c. The rest of the elements are packed in a list and assigned to
the variable d.
Unpack Tuple into a List in Python
We can also use the tuple unpacking operation to create a list directly from a tuple. For this, we will use
the following syntax.
myList=[*myTuple]
myTuple=(1,12,11,14,123,32,76,114,56)
print("The tuple is:",myTuple) #The tuple is: (1, 12, 11, 14, 123, 32, 76, 114, 56)
myList=[*myTuple]
print("The list is:",myList) #The list is: [1, 12, 11, 14, 123, 32, 76, 114, 56]
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 35
BUILT-IN FUNCTION ENUMERATE
• Earlier, we called range to produce a sequence of index values, then accessed
list elements in a for loop using the index values and the subscription
operator ([ ]). This is error-prone because we could pass the wrong
arguments to range. If any value produced by range is an out-of-bounds index,
using it as an index causes an IndexError.
• The preferred mechanism for accessing an element’s index and value is the
built-in function enumerate. This function receives an iterable and creates an
iterator that, for each element, returns a tuple containing the element’s index
and value.
• enumerate() is a useful tool for iterating over iterable objects while keeping
track of the index, which can simplify code and make it more efficient in
various programming situations.
• colors = ['red', 'orange', 'yellow']
• print(list(enumerate(colors))) #[(0, 'red'), (1, 'orange'), (2, 'yellow')]
• print(tuple(enumerate(colors))) #((0, 'red'), (1, 'orange'), (2, 'yellow'))
• for index, value in enumerate(colors):
• print(f'{index}: {value}')
• #0: red
• #1: orange
• #2: yellow
Programming-1(Python) [Link]. First Sem Surbhi Chhabra 36