[go: up one dir, main page]

0% found this document useful (0 votes)
10 views36 pages

Python List&Tuple

This document provides an introduction to lists and tuples in Python, highlighting their importance as sequence datatypes. It explains how to create lists, perform indexing and slicing, and manipulate list elements through operations such as appending, updating, and deleting. Additionally, it covers the use of the range() function, list concatenation, repetition, membership testing, and the concepts of aliasing and cloning lists.

Uploaded by

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

Python List&Tuple

This document provides an introduction to lists and tuples in Python, highlighting their importance as sequence datatypes. It explains how to create lists, perform indexing and slicing, and manipulate list elements through operations such as appending, updating, and deleting. Additionally, it covers the use of the range() function, list concatenation, repetition, membership testing, and the concepts of aliasing and cloning lists.

Uploaded by

veena more
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

INTRODUCTION TO PYTHON PROGRAMMING Unit III

UNIT – IV
LIST AND TUPLES
A sequence is a datatype that represents a group of elements. The purpose of any
sequence is to store and process a group of elements. In Python, strings, lists, tuples and
dictionaries are very important sequence datatypes. All sequences allow some common
operations like indexing and slicing.

LIST
A list is similar to an array that consists of a group of elements or items. Just like an
array, a list can store elements. But, there is one major difference between an array and a
list. An array can store only one type of elements whereas a list can store different types
of elements. Hence lists are more versatile and useful than an array. Perhaps lists are the
most used datatype in Python programs.

In our daily life, we do not have elements of the same type. For example, we take marks
of a student in 5 subjects:

50, 55, 62, 74, 66

These are all belonging to the same type, i.e. integer type. Hence, we can represent such
elements as an array. But, we need other information about the student, like his roll
number, name, gender along with his marks. So, the information looks like this:
10, Venu gopal, M, 50, 55, 62, 74, 66

Here, we have different types of data. Roll number (10) is an integer. Name (‘Venu
gopal’) is a string. Gender (‘M’) is a character and the marks (50, 55, 62, 74, 66) are again
integers. In daily life, generally we have this type of information that is to be stored and
processed. This type of information cannot be stored in an array because an array can
store only one type of elements. In this case, we need to go for list datatype. A list can
store different types of elements. To store the student's information discussed so far, we
can create a list as:
student = [10, ‘venu gopal', 'M', 50, 55, 62, 74, 66]

Please observe that the elements of the 'student' list are stored in square braces []. We
can create an empty list without any elements by simply writing empty square braces as:
e_lst = [] # this an empty list

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 1


INTRODUCTION TO PYTHON PROGRAMMING Unit III

Thus we can create a list by embedding the elements inside a pair of square braces []
The elements in the list should be separated by a comma (, ). To view the elements of a
list as a whole, we can simply pass the list name to the print() function as:
print(student)

The list appears as given below:


[10, 'Venu gopal', 'M', 50, 55, 62, 74, 66]

Indexing and slicing operations are commonly done on lists. Indexing represents
accessing elements by their position numbers in the list. The position numbers start
from 0 onwards and are written inside square braces as: student[0], student[1], etc... It
means student[0] represents 0th element, student[1] represents 1st element and so
forth. For example, to print the student's name, we can write:
print(student [1])

The name of student appears as given below:


Venu gopal
Slicing represents extracting a piece of the list by mentioning starting and ending
position numbers. The general format of slicing is: [start: stop: stepsize]. By default
'start' will be 0, 'stop' will be the last element and 'stepsize' will be 1. For example
student[0:3:1] represents a piece of the list containing 0th to 2nd elements.
print (student [0: 3:1])

The elements are given below:


[10, 'Venu gopal','M']

We can also write the above statement as:


print (student [: 3:])
The same elements appears as shown following:
[10, 'venu gopal', 'M']
Here, since we did not mention the starting element position, it will start at 0 and
stepsize will be taken as 1. Suppose, we do not mention anything in slicing, then the total
list will be extracted as:
print (student [: :])

It displays the output as:


[10, ‘Venu gopal', 'M, 50, 55, 62, 74, 66]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 2


INTRODUCTION TO PYTHON PROGRAMMING Unit III

Apart from indexing and slicing, the 5 basic operations: finding length, concatenation,
repetition, membership and iteration operations can be performed on lists and other
sequences like strings, tuples or dictionaries.

In the following program, we are creating lists with different types of elements and also
displaying the list elements.

CREATING LISTS USING RANGE() FUNCTION


We can use range() function to generate a sequence of integers which can be stored in a
list. The format of the range() function is:

range (start, stop, stepsize)


If we do not mention the 'start', it is assumed to be 0 and the 'stepsize' is taken as 1. The
range of numbers stops one element prior to 'stop'. For example,

range (0, 10, 1)

This will generate numbers from 0 to 9, as: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. Consider another
example:
range (4,9,2)

The preceding statement will generate numbers from 4th to 8th in steps , of 2, i.e.
(4,6,8).

In fact, the range() function does not return list of numbers. It returns only range class

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 3


INTRODUCTION TO PYTHON PROGRAMMING Unit III

object that stores the data about 'start, 'stop' and 'stepsize'. For example, if we write:
print (range (4,9,2))
The preceding statement will display:
range (4, 9, 2) # this is the object given by range ()

This range object should be used in for loop to get the range of numbers desired by the
programmer. For example:
for i in range(4,9,2):
print(i)
The preceding statement will display 4, 6, 8. Hence, we say range object is ‘iterable', that
is, suitable as a target for functions and loops that expect something from which they
can obtain successive items. For example, range object can be used in for loops to
display the numbers, or with list() function to create a list. In the following example, the
range() function is used in the list() function to create a list:
lst = list (range (4, 9, 2))
print(lst)
The list is shown below:
[4, 6, 8]
If we are not using the list() function and using range() alone to create a list, then we
will have only range class object returned by the range() function. For example,
lst = range (4, 9, 2)
print(lst)
The preceding statements will give the following output:
range (4, 9, 2) # this is not a list, it is range object

In this case, using a loop like for or while is necessary to view the elements of the list.
For example,
for i in lst:
print (i)
will display 4, 6, 8. In Program 2, we are showing examples of how to create lists using
the range() function. In this program, we are not using the list() function.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 4


INTRODUCTION TO PYTHON PROGRAMMING Unit III

We can use while loop or for loop to access elements from a list. The len() function is
useful to know the number of elements in the list. For example, len(list) gives total
number of elements in the list. The following while loop retrieves starting from 0th to
the last element of the list:
i=0
while i<len(list): # repeat from 0 to length of list
print(list[i])
i=i+1

Observe the len(list) function in the while condition as: while i<len(list). This will
return the total number of elements in the list. If the total number of elements is ‘n',
then the condition will become: while(i<n). It means i values are changing from 0 to n-
1. Thus this loop will display all elements of the list from 0 to n-1.

Another way to display elements of a list is by using a for loop, as:


for i in list: # repeat for all elements
print(i)
Here ‘i' will assume one element at a time from the list and hence if we display ‘i’ value,
it will display the elements one by one. In Program 3, we are showing how to access the
elements of a list using a while loop and a for loop.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 5


INTRODUCTION TO PYTHON PROGRAMMING Unit III

UPDATING THE ELEMENTS OF A LIST


Lists are mutable. It means we can modify the contents of a list. We can append, update
or delete the elements of a list depending upon our requirements.

Appending an element means adding an element at the end of the list. To append a new
element to the list, we should use the append() method. In the following example, we
are creating a list with elements from 1 to 4 and then appending a new element 9,
lst = 1ist(range (1, 5)) # create a list using 1ist() and range()
print(lst)
The preceding statements will give the following output:
[1, 2, 3, 4]

Now, consider the following statements:


lst.append (9) # append a new element to lst
print(lst)
The preceding statements will give the following output:
[1, 2, 3, 4, 9]

Updating an element means changing the value of the element in the list. This can be
done by accessing the specific element using indexing or slicing and assigning a new
value. Consider the following statements:
lst [1]= 8 # update 1st element of 1st
print(lst)
The preceding statements will give:
[1, 8, 3, 4, 9]

Consider the following statements:


lst [1:3] = 10, 11 #update 1st and 2nd elements of lst
print(lst)
The preceding statements will give:
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 6
INTRODUCTION TO PYTHON PROGRAMMING Unit III

[1, 10, 11, 4, 9]


Deleting an element from the list can be done using 'del' statement. The del statement
takes the position number of the element to be deleted.
del lst [1] # delete 1st element from lst
print(lst)
Now, the list appears as:
[1, 11, 4, 9]

We can also delete an element using the remove() method. In this method, we should
pass the element to be deleted.
lst.remove (11) # delete 11 from lst
print (lst)
Now, the list appears as:
[1, 4, 9]

let's write a program to retrieve the elements of a list in reverse order. This can be done
easily by using the reverse() method, as:
list.reverse()
This will reverse the order of elements in the list and the reversed elements are
available in the list. Suppose, we do not have the reverse() method, then how can we
develop logic to display the elements in reverse order? This can be done using while
loop and accessing the elements in reverse order. For example, let's assume a list with 5
elements. The positions of these elements can be specified using indexing, as: list[0] to
list[4] . To display in reverse order, we should follow the order: list[4] to list[0]. The
following while loop can be used to display the list in reverse order:
while i>=0: #i represents initially 4.
print(list[il) # display from 4th to 0th elements
i-=1 # decrease the position every time.

In the previous code, ‘i’ starts with a value ‘n-1' where ‘n' represents the number of
elements of the list. Thus if the list has 5 elements, i would start from 4th element
onwards till 0th element.

Another way to access elements in reverse order is by using negative indexing. When
we write list[-1], it represents the last element. List[-2] represents 2nd element from the
end. Hence, we should display from list[-1] to list[-5] so that the list will be displayed in
reverse order.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 7


INTRODUCTION TO PYTHON PROGRAMMING Unit III

i=-1 # last element


while i>=-5: # dísplay from -1th to -5th elements
print(days [i])
i-=1 # decrease the position every time

This logic is shown in Program 4 where we are displaying the elements of a list in
reverse order using while loop in two different ways.

CONCATENATION OF TWO LISTS


We can simply use ‘+' operator on two lists to join them. For example, ‘x' and ‘y' are two
lists. If we write x+y, the list ‘y' is joined at the end of the list ‘x'.
x=[10, 20,30,40, 50]
y = [100, 110, 120]
print (x+y) # concatenate x and y
The concatenated list appears:
[10, 20, 30, 40, 50, 100, 110, 120]

REPETITION OF LISTS
We can repeat the elements of a list ‘n' number of times using ‘*’ operator. For example,
if we write x*n, the list x will be repeated for n times as:
print (x*2)# repeat the list x for 2 times

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 8


INTRODUCTION TO PYTHON PROGRAMMING Unit III

Now, the list appears as:


[10, 20, 30, 40, 50, 10, 20, 30, 40, 50]

MEMBERSHIP IN LISTS
We can check if an element is a member of a list or not by using ‘in' and 'not in'
operator. If the element is a member of the list, then ‘in' operator returns True else
False. If the element is not in the list, then ‘not in' operator returns True else False. See
the examples below:
x=[10, 20,30,40, 50]
a = 20
print (a in x) # check if a is member of x
The preceding statements will give:
True
If you write,
print (a not in x) # check if a is not a member of x
Then, it will give
False

ALIASING AND CLONING LISTS


Giving a new name to an existing list is called 'aliasing’. The new name is called 'alias
name'. For example, take a list ‘x' with 5 elements as
x=[10, 20,30,40, 50]
To provide a new name to this list, we can simply use assignment operator as:

y=x

In this case, we are having only one list of elements but with two different names ‘x' and
‘y’. Here, 'x' is the original name and ‘y' is the alias name for the same list. Hence, any
modifications done to ‘x' will also modify ‘y' and vice versa. Observe the following
statements where an element x[1] is modified with a new value. This is shown in
Figure 10.1.
x = [10,20,30,40, 50]
y =x #x is aliased as y
print(x) will display [10, 20, 30,40,50]
print (y) will display [10,20,30,40,50]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 9


INTRODUCTION TO PYTHON PROGRAMMING Unit III

Hence, if the programmer wants two independent lists, he should not go for aliasing, on
the other hand, he should use cloning or copying.
Obtaining exact copy of an existing object (or list) is called cloning. To clone a list, we
can take help of the slicing operation as:
y=x[:] # x is cloned as y

When we clone a list like this, a separate copy of all the elements is stored into ‘y’. The
lists ‘x' and 'y' are independent lists. Hence, any modifications to ‘x' will not affect 'y’
and vice versa. Consider the following statements:

We can observe that in cloning, modifications to a list are confined only to that list. The
same can be achieved by copying the elements of one list to another using copy()
method. For example, consider the following statement:
y=x.copy() # x is copied as y
When we copy a list like this, a separate copy of all the elemnts is stored into ‘y’. The
lists ‘x’ and ‘y' are independent. Hence, any modifications to ‘x' will not affect ‘y’ and

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 10


INTRODUCTION TO PYTHON PROGRAMMING Unit III

vice versa. Figure 2 depicts the concept of cloning and copying.

METHODS TO PROCESS LISTS


The function len() is useful to find the number of elemnts in a list. We can use this
function as:
n = len(list)
Here, ‘n’ indicates the number of elements of the list. Similar to len() function, we have
max) function that returns biggest element in the list. Also, the min() function returns
the smallest element in the list. Other than these function, there are various other
methods provided by Python to perform various operations on lists. These methods are
shown in Table 10.1:

We have used these methods in Program 5 to understand how these methods used on
an example list.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 11


INTRODUCTION TO PYTHON PROGRAMMING Unit III

FINDING BIGGEST AND SMALLEST ELEMENTS IN A LIST


Python provides two functions, max() and min(), which return the biggest and smallest
elements from list. For example, if the list is x, then:
n1 = max (x) # n1 gives the biggest element
n2=min (x) # n2 gives the smallest element
If we do not want to use these functions, but want to find the biggest and smallest
elements in the list, how is it possible? For this purpose, we should develop our own
logic.

First of all, we will store the elements in a list. Let's take the example list as:
x= [20, 10, 5, 20, 15]
he list elements here are represented as x[0], x[1], .. x(4]. That means the elements in
he list are in general represented as x[i]. We will take the first element as the biggest
and also as the smallest one as:
big=x[0]
small=x [0]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 12


INTRODUCTION TO PYTHON PROGRAMMING Unit III

We will compare ‘big' and 'small' elements with other elements in the list. If the other
element is > big, then it should be taken as ‘big’. That means,
if x[i]>big: big= x[i]
Similarly, if the other element is < 'small', we should take that other element as 'small ‘
as:
if x[i]<small: small = x[1]
Since the comparison starts from 1st element onwards, ‘i’ value will change from 1 till
the end of the list. This logic is used in Program 6.

SORTING THE LIST ELEMENTS


Python provides the sort() method to sort the elements of a list. This method can be
used as:
x.sortO
This will sort the list 'x' into ascending order. If we want to sort the elements of the
into descending order, then we can mention ‘reverse=True' in the sort() method as:
x. sort(reverse=True)
This will sort the list x' into descending order.
Suppose, we want to sort a list without using sort() method, we have to develop our
own logic like bubble sort technique. In this technique, all the ‘n' elements from 0 to n
are taken and the first element of the list x[j] is compared with the immediate element

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 13


INTRODUCTION TO PYTHON PROGRAMMING Unit III

x[j+1]. If x[j] is bigger than x[j+1], then they are swapped (or interchanged) since in
ascending order we expect the smaller elements to be in the first place. When two
elements are interchanged, the number of elements to be sorted becomes lesser by 1.
When there are no more swaps found, the ‘flag' will become ‘False' and we can abort
sorting. Suppose, we give the following elements for sorting:

Swapping means interchanging the values of two variables. If 'a' and b' are variables,
we are supposed to store 'a' value into ‘b' and vice versa. Swapping the values of 'a'
and ‘b’ can be done using a temporary variable ‘t’ as:
store a value into t. i.e. t=a
store b value into a. i.e. a =b
store t value into b. i.e. b= t
These steps are shown in Figurel0.3 by taking 'a' value 1 and ‘b' value 2 initially. After
swapping is done, 'a' value will be 2 and ‘b' value will be 1.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 14


INTRODUCTION TO PYTHON PROGRAMMING Unit III

NUMBER OF OCCURRENCES OF AN ELEMENT IN THE LIST


Python provides count() method that returns the number of times a particular
element is repeated in the list. For example,
n= x.count(y)
will return the number of times ‘y' is found in the list x'. This method returns 0 if the
element is not found in the list.
It is possible to develop our own logic for the count() method. Let's take ‘y' as the
element to be found in the list x. We will use a counter ‘c’ that counts how many times
the element ‘y' is found in the list ‘x’. Initially ‘c’ value will be 0. When ‘y' is found in the
list, ‘c' will increment by 1. We need a for loop that iterates over all the elements of the
list as:
for i in x:

This for loop stores each element from the list ‘x' into ‘i’. So, if ‘y ==i' we found the

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 15


INTRODUCTION TO PYTHON PROGRAMMING Unit III

element and hence we should increment i value by 1. This is shown by the following
code snippet:
c=0
for i in x:
if(y==i): c+=1
print('{} is found (} times. '. format (y, c))
The above code represents our own logic to find the number of occurrences of ‘y’ in
the list ‘x’. The same is shown in Program 8.

FINDING COMMON ELEMENTS IN TWO LISTS


Sometimes, it is useful to know which elements are repeated in two lists. For example,
scholarship for which another group of students enrolled in a college. There is another
scholarship for which another group of students enrolled. Now we want to know the r
names of the students who enrolled for both the scholarships so that we can restrict
them to take only one scholarship. That means, we are supposed to find out the
common students (or elements) in both the lists.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 16


INTRODUCTION TO PYTHON PROGRAMMING Unit III

Lets take the two groups of students as two lists. First of all, we should convert the
lists into sets, using set() function, as: set(list). Then we should find the common
elements in the two sets using intersection() method as:
set1.intersection (set2)
This method returns a set that contains common or repeated elements in the two sets.
This gives us the names of the students who are found in both the sets. This logic is
presented in Program 9.

STORING DIFFERENT TYPES OF DATA IN A LIST


The beauty of lists is that they can store different types of elements. For example, we
can store an integer, a string a float type number etc. in the same string. It is also
possible to retrieve the elements from the list. This has advantage for lists over arrays.
We can create, list 'emp' as an empty list as:
emp = []
Then we can store employee data like id number, name and salary details into the
‘emp’ list using the append() method. After that, it is possible to retrieve employee
details depending on id number of the employee. This is shown in Program 10.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 17


INTRODUCTION TO PYTHON PROGRAMMING Unit III

NESTED LISTS
A list within another list is called a nested list. We know that a list contains several
elements. When we take a list as an element in another list, then that list is called a
nested list. For example, we have two lists 'a' and b' as:
a = [80, 90]
b=[10, 20, 30, a]
Observe that the list 'a' is inserted as an element in the list ‘b' and hence 'a' is called a
nested list. Let's display the elements of ‘b', by writing the following statement:
print (b)
The elements of b appears:
[10, 20, 30, [80, 90]]
The last element [80, 90] represents a nested list. So, ‘b' has 4 elements and they are:
b[0] = 10
b[1] = 20
b[2] = 30
b[3] = [80, 90]
So, b[3] represents the nested list and if we want to display its elements separately, we
can use a for loop as:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 18


INTRODUCTION TO PYTHON PROGRAMMING Unit III

for x in b[3]:
print(x)

In Program 11, we used a for loop to display the nested list. We can refer to the
individual elements of the nested list, as:
list[3][0]# represents 80
list[3][1]# represents 90
One of the main uses of nested lists is that they can be used to represent matrices. A
matrix represents a group of elements arranged in several rows and columns. If a
matrix contains ‘m’ rows and ‘n' columns, then it is called m x n matrix. In python
matrices are created as 2D arrays or using matrix object in numpy. We can also create
a matrix using nested lists.

NESTED LISTS AS MATRICES

Suppose we want to create a matrix with 3 rows and 3 columns, we should create a list
with 3 other lists as:
mat = [[1, 2, 3], [4,5,6], [7,8,9]]

Here ‘mat' is a list that contains 3 lists which are rows of the ‘mat' list. Each row
contains again 3 elements as:
[[1,2.3] , #first row
[4.5,6], #second row
[7,8,9] #third row
If we use a for loop to retrieve the elements from ‘mat’, it will retrieve row by row as:
for r in mat:
print(r) #display row by row

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 19


INTRODUCTION TO PYTHON PROGRAMMING Unit III

But we want to retrieve columns (or elements) in each row; hence we need another
for loop inside the previous loop as:
for r in mat:
for c in r: #display columns in each row
print(c, end= ‘ ‘)
print()
Another way to display the elements of a matrix is using indexing. For example, mat[i]
[j] represents the ith row and jth column element. Suppose the matrix has 'm' rows
and ‘n’ columns, we can retrieve the elements as:
for i in range(len (mat)): # i values change from 0 to m-1
for j in range(len (mat [i])): #j values change from 0 to n-1
print('%d’ %mat [i][j], end=’ ‘)
Program 12 shows various ways of displaying the elemnts of matrix.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 20


INTRODUCTION TO PYTHON PROGRAMMING Unit III

We can create two matrices using nested lists and find their sum matrix This is shown
in Program 13. In this program, m1 and m2 represent matrix of 3 rows and 4 columns
each. To add them we need a simple logic where the elements in corresponding
positions in the two matrices are added, as:
m3[i] [j]= ml[i] [j] +m2 [i][j]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 21


INTRODUCTION TO PYTHON PROGRAMMING Unit III

LIST COMPREHENSIONS
List comprehensions represent creation of new lists from an iterable object (like a list,
set, tuple, dictionary or range) that satisfy a given condition. List comprehensions
contain very compact code usually a single statement that performs the task.

Example 1: We want to create a list with squares of integers from 1 to 10. We can
write code as:
squares = [] #Create empty 1ist
for x in range(1, 11): # repeat x values from 1 to 10
squares.append (x**2) # add squares of x to the list

The preceding code will create 'squares' list with the elements as shown below:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The previous code can be rewritten in a compact way as:


squares = [x**2 for x in range (1, 11)]

This is called list comprehension. From this, we can understand that a list
comprehension consists of square braces containing an expression (i.e. x**2). After the
expression, a for loop and then zero or more if statements can be written. Consider the
following syntax:
[expression for item1 in iterable1 if statement1
for item2 in iterable2 if statement2
for item3 in iterable3 if statement3……]
Here, ‘iterable' represents a list, set, tuple, dictionary or range object. The result of a

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 22


INTRODUCTION TO PYTHON PROGRAMMING Unit III

list comprehension is a new list that contains elements as a result of executing the
expression according to the for loops and if statements. So, we can store the result of a
list comprehension in a new list.

Example 2: Suppose, we want to get squares of integers from 1 to 10 and take


only the even numbers from the result, we can write a list comprehension as:
even squares = [x**2 for x in range (1, 11) if x % 2==0]

If we display the list 'even_squares', it will display the following list:


[4, 16, 36, 64, 100]
The same list comprehension can be written without using the if statement as:
even_squares = [x**2 for x in range(2, 11, 2)]

Example 3: If we have two lists ‘x' and ‘y' and we want to add each element of ‘x'
with each element of ‘y', we can write for loops as:
x = [10, 20, 30]
y= [1, 2, 3, 4]
lst[ ]
for i in x:
for j in y:
lst.append(i+j)

Here, the resultant list ‘lst' contains the following elements:


[11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34]
The same result can be achieved by using list comprehension as:
lst = [i + j for i in x for j in y]
or we can directly mention the lists in the list comprehension as:
lst = [i+j for i in [10, 20, 30] for j in [1,2,3,4]]
The previous list comprehension can be written using strings as:
lst = [ i+j for i in 'ABC' for j in 'DE’]
In this case, the output will be:
['AD', 'AE', 'BD', 'BE', 'CD','CE']

Example 4: Let's take a list ‘words' that contains a group of words or strings as:
words =['Apple', ‘Grapes', ‘Banana', ’orange']
We want to retrieve only the first letter of each word from the above list and store
those first letters into another list ‘lst’. We can write code as:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 23


INTRODUCTION TO PYTHON PROGRAMMING Unit III

lst = []
for w in words:
lst. append (w[0])
Now, lst contains the following letters:
['A', 'G', 'B','O']
This task can be achieved through list comprehension as:
lst = [w[0] for w in words]

Example 5: Let's take two lists 'num1' and 'num2' with some numbers as:
num1 = [1,2,3,4, 5]
num2 = [10, 11,1,21
We want to create another list 'num3' with numbers present in 'num1' but not in
‘num2’. We can develop the logic like this:
num3= []
for i in num1:
if i not in num2:
num3.append (i)
If we display 'num3' we can see the following elements:
[3, 4, 5]
The same can be achieved using list comprehension as:
num3 = [i for i in num1 if i not in num2]

Example 6: Like list comprehensions, it is also possible to create set


comprehensions and dictionary comprehensions in the same manner as
discussed in the previous examples. Let's see how to create a dictionary
comprehension. A dictionary contains key and value pairs separated by colons.
A dictionary uses curly braced to embed the elements. We take a dictionary with
hall ticket number and student name as:
dict= {1001: 'Pratap’, 1002:’Mohan' , 1003: ‘Ankita' }

Here, 1001 is hall ticket number of the student and ‘Pratap' is the name of the student.
The hall ticket number is called key and the name is called its value. We can create
dictionary comprehension to convert keys as values and vice versa as:
dict1 = {value: key for key,value in dict.items ()}
Here, dict.items() represents all items in the dictionary in the form of key value pairs.
In the above expression, we are writing value: key which is the reverse order for
writing key and value pairs. If we display ‘dict1', it will show:
{'Pratap': 1001, ‘Ankita': 1003, ‘Mohan’: 1002}

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 24


INTRODUCTION TO PYTHON PROGRAMMING Unit III

TUPLES

A tuple is a Python sequence which stores a group of elements or items. Tuples are
similar to lists but the main difference is tuples are immutable whereas lists are
mutable. Since tuples are immutable, once we create a tuple we cannot modify its
elements. Hence we cannot perform operations like append(), extend(), insert(),
remove(), pop() and clear() on tuples. Tuples are generally used to store data which
should not be modified and retrieve that data on demand.

CREATING TUPLES
We can create a tuple by writing elements separated by commas inside parentheses ().
The elements can be of same datatype or different types. For example, to create an
empty tuple, we can simply write empty parenthesis, as:
tupl = ( )# empty tuple
Jf we want to create a tuple with only one element, we can mention that element in
parentheses and after that a comma is needed, as:
tup2 = (10,) # tuple with one element. observe comma after the element
Here is a tuple with different types of elements:
tup3 = (10, 20, -30.1, 40.5,’Hyderabad', 'New Delhi')
We can create a tuple with only one of type of elements also, like the following:
tup4 = (10, 20, 30) # tuple with integers
If we do not mention any brackets and write the elements separating them by
commas, then they are taken by default as a tuple. See the following example:
tup5 = 1, 2, 3, 4 #no braces
The point to remember is that if do not use any brackets, it will become a tuple and not
a list or any other datatype.

It is also possible to create a tuple from a list. This is done by converting a list into a
tuple using the tuple() function. Consider the following example:
list = [1, 2, 3] #take a list
tpl = tuple(1ist) # convert list into tuple
print(tpl)# display tuple

The tuple is shown below:


(1, 2, 3)
Another way to create a tuple is by using range() function that returns a sequence. To
create a tuple ‘tpl' that contains numbers from 4 to 8 in steps of 2, we can use the
range() function along with tuple() function, as:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 25


INTRODUCTION TO PYTHON PROGRAMMING Unit III

tpl= tuple (range (4, 9, 2)) # numbers from 4 to 8 in steps of 2


print (tpl)

The preceding statements will give:


(4, 6, 8)

ACCESSING THE TUPLE ELEMENTS


Accessing the elements from a tuple can be done using indexing or slicing. This is same
as that of a list. For example, let's take a tuple by the name ‘tup' as:
tup = (50, 60, 70, 80,90, 100)
Indexing represents the position number of the element in the tuple. Now, tup[0]
represents the 0th element, tup[1] represents the 1st element and so on.
print (tup [0])

The preceding will give:


50
Now, if you write:
print (tup [5])

Then the following element appears:


100
returns a ser
print (tup[-1])
Then the following element appears:
100
Similarly, negative indexing is also possible. For example, tup[-1] indicates the last
element and tup[-2] indicates the second element from the end and so on. Consider
the following statement:
print (tup[-1])
The preceding statement will give:
100
If you write,
print(tup[-6])
Then the following output appears:
50
Slicing represents extracting a piece or part of the tuple. Slicing is done in the format:
[start: stop: stepsize]. Here, 'start' represents the position of the starting element and
‘stop' represents the position of the ending element and the 'stepsize' indicates the
incrementation. If the tuple contains n' elements, the default values will be 0 for ‘start'

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 26


INTRODUCTION TO PYTHON PROGRAMMING Unit III

and n-1 for 'stop' and 1 for 'stepsize'. For example, to extract all the elements from the
tuple, we can write:
print(tup[:])
The elements of tuple appear:
(50, 60, 70, 80, 90, 100)
For example, to extract the elements from 1st to 4th , we can write:
print (tup [1:4])
The elements of tuple appear:
(60, 70, 80)
Similarly, to extract every other element, i.e. alternate elements, we can write:
print (tup[::2]) # here, start and stop assume default values.
The following output appears:
(50, 70, 90)
Negative values can be given in the slicing. If the 'step size' is negative, the elements
are extracted in reverse order as:
print (tup[::-2])
The elements appear in the reverse order:
(100, 80, 60)

When the step size is not negative, the elements are extracted from left to right. In the
following example, starting position -4 indicates the 4th element from the last. Ending
position -1 indicates the last element. Hence, the elements from 4th to one element
before the ending element (left to right) will be extracted.
print(tup[-4:-1]) # here, step size is1
The following elements appear:
(70, 80, 90)
In most of the cases, the extracted elements from the tuple should be stored in
separate variables for further use. In the following example, we are extracting the first
two elements from the 'student' tuple and storing them into two variables.
student = (10, 'Vinay kumar', 50,60,65,61,70)
rno, name = student [0 :2]

Now, the variable ‘rno' represents 10 and 'name' represents Vinaykumar. Consider the
following statement:
print (rno)
The preceding statement will give:
10
Now, if you write:
print (name)

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 27


INTRODUCTION TO PYTHON PROGRAMMING Unit III

The preceding statement will provide the name of the student:


Vinay kumar
If we want to retrieve the marks of the student from 'student' tuple, we can do it as:
marks = student [2 :7] # store the elements from 2nd to 6th into ‘marks’
# tuple
for i in marks:
print(i)
The preceding statements will give the following output:
50
65
60
61
70

BASIC OPERATIONS ON TUPLES


The 5 basic operations: finding length, concatenation, repetition, membership and
iteration operations can be performed on any sequence may be it is a string, list, tuple
or a dictionary.

To find length of a tuple, we can use len() function. This returns the number of
elements in the tuple.

Consider the following example:


student = (10, 'Vinaykumar, 50,60,65,61,70)
len(student)

The preceding statement will give the following output:


7

We can concatenate or join two tuples and store the result in a new tuple. For example
the student paid a fees of Rs. 25,000.00 every year for 4 terms, then we can create a
‘fees’ tuple as:
fees (25000.00,) *4 # repeat the tuple elements for 4 times.
print (fees)
The preceding statement will give the following output:
(25000.0, 25000.0, 25000.0, 25000.0)

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 28


INTRODUCTION TO PYTHON PROGRAMMING Unit III

Now, we can concatenate the ‘student' and fees tuples together to form a new tuple
‘students1’ as:
student1 = student+fees
print(student1)

The preceding statement will give:


(10, ‘vinay kumar’, 50, 60, 65, 61, 70, 25000.0, 25000.0, 25000.0, 25000.0)
searching whether an element is a member of the tuple or not can be done using ‘in'
and ‘not in’ operators. The ‘in' operator returns True if the element is a member. The
'not in' operator returns true if the element is not a member. Consider the following
statements:
name=’Vinay kumar’ # to know if this is member of student1 or not
name in student1
The preceding statements will give:
True

Suppose if you write:


name not in student1
Then the following output will appear:
False
The repetition operator repeats the tuple elements. For example, we take a tuple ‘tpl'
and repeat its elements for 4 times as:
tpl = (10, 11, 12)
tpl1 = tpl*3
print (tpl1)

The preceding statements will give the following output:


(10, 11, 12, 10, 11, 12, 10, 11, 12)

FUNCTIONS TO PROCESS TUPLES


There are a few functions provided in Python to perform some important operations
on tuples. These functions are mentioned in Table 10.2. Any function is called directly
with its name. In this table, count() and index() are not functions. They are methods.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 29


INTRODUCTION TO PYTHON PROGRAMMING Unit III

Hence, they are called in the format: object.method().

We will write a program to accepts elements of a tuple from the keyboard and find
their sum and average. In this program, we are using the following statement to accept

elements from the keyboard directly in the format of a tuple (i.e. inside parentheses)
num=eval(input(“Enter elements in ( ): “))
The eval() function is useful to evaluate whether the typed elements are a list or a
tuple depending upon the format of brackets given while typing the elements. If we
type the elements inside the square braces as: [1,2,3,4,5] then they are considered as
elements of a list. If we enter the elements inside parentheses as: (1,2,3,4,5), then they
are considered as elements of a tuple. Even if do not type any brackets, then by default
They are taken as elements of tuple.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 30


INTRODUCTION TO PYTHON PROGRAMMING Unit III

When the above program asks the user for entering the elements, the user can type
the elements inside the parentheses as: (1,2,3,4,5,6) or without any parentheses as
1,2,3,4,5,6. When a group of elements are entered with commas (, ), then they are by
default taken as a tuple in Python.

In Program 15, first we enter the elements separated by commas. These elements are
stored into a string 'str as:

str=input(‘Enter elements separated by commas: ‘).split(‘ , ‘)

Then each element of this string is converted into integer and stored into a list ‘lst' as:
lst = [int (num) for num in str]
This list can be converted into a tuple using tuple() function as:
tup = tuple(lst)
Later, index() method is used to find the first occurrence of the element 'ele’ as:
pos = tup.index (ele) # returns first occurrence of element

If the ‘ele' is not found in the tuple, then there will be an error by the name
‘ValueError’ which should be handled using try and except blocks which is shown in
the program.

NESTED TUPLES
A tuple inserted inside another tuple is called nested tuple. For example,
tup = (50,60,70, 80,90, (200, 201)) # tuple with 6 elements
Observe the last parentheses in the tuple ‘tup', i.e. (200, 201). These parentheses

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 31


INTRODUCTION TO PYTHON PROGRAMMING Unit III

represent that it is a tuple with 2 elements inserted into the tuple ‘tup’. The tuple (200,
201) is called nested tuple as it is inside another tuple.

The nested tuple with the elements (200, 201) is treated as an element along with
other elements in the tuple ‘tup'. To retrieve the nested tuple, we can access it as an
ordinary element as tup[5] as its index is 5. Now, consider the following statement:
print("Nested tuple=’, tup[6])
The preceding statement will give the following output:
Nested tuple= (200, 201)
Every nested tuple can represent a specific data record. For example, to store 4
employees data in 'emp' tuple, we can write:

emp = ((10, "Vijay", 9000. 90), (20, "Nihaar", 5500.75), (30, "vanaja", 8900. 00),
(40, "Kapoor", 5000.50))

Here,’emp' is the tuple name. It contains 4 nested tuples each of which represents the
data of an employee. Every employee's identification number, name and salary are
stored as nested tuples.

Sorting Nested Tuples


To sort a tuple, we can use sorted() function. This function sorts by default into,
ascending order. For example,
print (sorted (emp) )

will sort the tuple 'emp' in ascending order of the 0th element in the nested tuples, ie
identification number. If we want to sort the tuple based on employee name, which is
the 1st element in the nested tuples, we can use a lambda expression as:
print(sorted (emp, key=lambda x: x[1])) # sort on name

Here, key indicates the key for the sorted() function that tells on which element
sorting should be done. The lambda function: lambda x: x(1] indicates that x[1] should
be taken as the key that is nothing but 1st element. If we want to sort the tuple based
on salary, we can use the lambda function as: lambda x: x[2]. Consider Program 16.

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 32


INTRODUCTION TO PYTHON PROGRAMMING Unit III

INSERTING ELEMENTS IN A TUPLE


Since tuples are immutable, we cannot modify the elements of the tuple once it is
created. Now, let's see how to insert a new element into an existing tuple. Let's take 'x’
as an existing tuple. Since ‘x' cannot be modified, we have to create a new tuple ‘y' with
the newly inserted element. The following logic can be used:

1. First of all, copy the elements of ‘x’ from 0th position to pos-2 position into ‘y' as:
y = x+[0:pos-1]
2. Concatenate the new element to the new tuple ‘y'.
y = y + new
3. Concatenate the remaining elements (from pos-1 till end) of x to the new tuple ‘y'.
The total tuple can be stored again with the old name ‘x’
x = y+x[pos-1:]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 33


INTRODUCTION TO PYTHON PROGRAMMING Unit III

This program works well with strings. Of course the same program can be used with
integers also, if we change the input statement that accepts an integer number as:
lst= [int(input('Enter a new integer: ‘))]

MODIFYING ELEMENTS OF A TUPLE


It is not possible to modify or update an element of a tuple since tuples are immutable.
If we want to modify the element of a tuple, we have to create a new tuple with a new
value in the position of the modified element. The logic used in the previous section
holds good with a slight difference in the last step. Let's take 'x' is the existing tuple
and ‘y’ is the new tuple.

1. First of all, copy the elements of 'x' from 0th position to pos-2 position into ‘y' as:
y= x[0:pos-1]
2. Concatenate the new element to the new tuple ‘y'. Thus the new element is stored in
position of the element being modified.
y = y+new
3.Now concatenate the remaining elements from ‘x' by eliminating the element which
is at pos-1. It means we should concatenate elements from ‘pos’ till the end. The total
tuple can be assigned again to the old name ‘x'.
x= y+x [pos:]
This logic is depicted in Figure 10.5 and shown in Program 18:

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 34


INTRODUCTION TO PYTHON PROGRAMMING Unit III

DELETING ELEMENTS FROM A TUPLE


The simplest way to delete an element from a particular position in the tuple is to copy
the elements into a new tuple except the element which is to be deleted. Let's assume
that the user enters the position of the element to be deleted as ‘pos'. The
corresponding position will be ‘pos-1' in the tuple as the elements start from 0th
position. Now the logic will be:

1. First of all, copy the elements of ‘x’ from 0th position to pos-2 position into ‘y’ as:
y = x[0:pos-1]
2 Now concatenate the remaining elements from 'x’ by eliminating the element which

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 35


INTRODUCTION TO PYTHON PROGRAMMING Unit III

is at pos-1. It means we should concatenate elements from ‘pos' till the end. The total
tuple can be assigned again to the old name ‘x’.
x= y+x[pos:]

ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 36

You might also like