List
List
List - A List is a standard mutable data type of python than can store a sequence of
values belonging to any data type. Lists are enclosed in square brackets and the
elements of the list are separated by commas.
Eg. [ ] - empty list
[1, 2, 3] - list of integers
['abc', 'def', 'ghi' ] - list of strings
Suppose if list name, L= [80, 60, 70, 85, 75]
Creating Lists
1. Creating empty list- Empty lists can be created by writing empty square brackets
or by using list() method with no parameters.
Eg.
L= []
L=list
()
2. Creating long list- If a list contains many elements, then the elements can be split
in the next line
Eg. L = [ 'abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz' ,
'abcdefghijklmnopqrstuvwxyz', '123456789' ]
3. Creating nested list- A list containing within itself another list is known as a nested
list.
Eg. L = [ 1 , 2, [ 3,4,5], 6 , 7, [8,9,10] ]
4. Creating list from existing sequence objects- A list can be created from a sequence
object ( such as other list, tuples, strings etc) by passing it as a parameter to the list()
function.
Eg. L1=list('hello') # creates the list with elements ['h', 'e', 'l', 'l', 'o']
5. Creating list from user input- The user input is always accepted as a string. This
string can be converted to a list object by passing it to either the function list() or to
the
function eval(). This list() function will try to convert the string to a list, whereas the
eval() function evaluates the string and finds which data type best matches the string.
If the string contains square brackets with values separated by commas then it creates
a list.
Eg. L1=list(input('Enter a list of marks')) # list() used
L2=eval(input(('Enter the list of holidays for the month:')) #eval used
List Operations
1. Displaying a List
Using print and passing a list object displays a list of elements in square brackets
separated by
commas.
L = [2,7,9,13,19]
print(L)
OUTPUT :
[2,7,9,13,19]
2. Accessing element of a List
An element of a list can be accessed by using the list name and an integer value
known as an index enclosed in square bracket, L[index].
There are two indexing methods - forward indexing and backward indexing.
• In forward indexing the first element of the list has index number 0, the second
element has index number 1 and so on.
• In backward indexing the last element of the list has index -1, the second last
element
has index -2 and so on.
• An element of a list can be accessed by using any one of the forward or backward
indexing methods.
Consider the list L= [ 2, 7, 9, 13, 19 ]
forward indexing ----
->
01234
L
= -5 -4 -3 -2 -1 <----- Backward
Indexing The element 9 of the list can be represented by either L[2] or by L[-3] , both
will refer
to the same element.
Eg.
L = [2,7,9,13,19]
print(L[2] )
print (L[-4])
OUTPUT :
9
7
3. Modifying a List element/Mutability of a List
The elements of a list can be modified by using L[index]=new_value. Since a list can
be
modified in place, i.e. the existing list object is not destroyed and recreated, the list
data type is
said to be mutable.
L=
[2,7,9,13,19]
L[2]=99
L[-1] =77
print
(L)
OUTPUT :
[2, 7, 99, 13, 77]
4. Joining/Concatenating two Lists
The + operator can be used to join/concatenate two lists.
L1 = [1,2,3]
L2=[7,8,9]
L3=L2+L1
print(L3 )
OUTPUT :
[7, 8, 9, 1, 2, 3]
5. Replicating Lists
The * operator can be used to replicate lists. The * operator when used with a list, one
of the
operands must be an int value that signifies the number of times the list is to be
replicated.
L1 = [1,2,3]
L2=L1*3
print(L2 )
OUTPUT :
[1, 2, 3, 1, 2, 3, 1, 2, 3]
6. Traversing a list using the index
The for loop can be used to go through all the valid indexes of the list and process the
list. For
this the len() function must be used to get count of number of elements of the list.
L1 = [9,3,2,4]
x=len(L1)
for i in range(x):
print(L1[i])
OUTPUT :
9
3
2
4
In this method L1[i] refers to the actual element of the list. Any updates done to L[i]
will
update the list in place. Use this method to update the list using for loop.
Traversing a list using the iterator
The for loop can be used to iterate over the elements of the list and process the list.
L1 = [9,3,2,4]
for i in L1:
print(i)
OUTPUT :
9
3
2
4
Here the loop variable i is only holding a copy of the list element. Any updates done
to i does
not affect the list in any way. So do not use this method if the list is to be updated
using loops.
8. List Comparisons
The relational operators >, >=, <, <=, ==, != can be applied to two lists to arrive at a
True or
False value. The following rules are observed:
a. For equality (==) operator - If equality evaluate to True only when all the
elements of one list match all the elements of the other list and both the list have the
same number of elements.
b. For all other operators - The elements are compared sequentially using the operator
under consideration. If a clear answer (either True or False) is arrived then that
becomes the result of the comparison between the two lists. A clear answer is not
arrived when elements of both the list happen to have same value. Then in that case
the next set of elements are checked and the process is repeated.
c. If two lists are of different lengths and if one of the list has an element at an index
position and the other list does not have an element at that position then the evaluation
proceeds as follows:
• something/somevalue > empty/nothing evaluates to True
• something/somevalue < empty/nothing evaluates to False
print( [1,2,3] == [1,2,3])
print( [1,2,3] != [1,2,3])
print( [1,2,8,9] < [9,1])
print( [1,2,8,9] >= [1,9])
print( [1,2] < [1,2,3])
print( [2] > [1,2,3])
OUTPUT :
True
False
True
False
True
True
9. List Slicing
List slice is creating a new list using elements of an existing list. It is created as:
ListName[start : stop : step] where start, stop , step are integers
The slice [start : stop : step] is used on many objects with index.
The basic rules of slice are:
i. The slice generates index/integers from - start, start + step, start + step + step, and
so on. All the numbers generated must be less than the stop value when step is
positive.
ii. If step value is missing then by default is taken to be 1
iii. If start value is missing and step is positive then start value is by default taken as 0.
iv. If stop value is missing and step is positive then start value is by default taken to
mean till you reach the ending index(including the ending index)
v. A negative step value means the numbers are generated in backwards order i.e.
from - start, then start - step, then start -step -step and so on. All the numbers
generated in negative step must be greater than the stop value.
vi. If start value is missing and step is negative then start value takes default value -1
vii. If stop value is missing and step is negative then stop value is by default
taken to be till you reach the first element (including the 0 index element)
Consider the list L:
forward indexing
----->
0123456789
L
= -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 <----- Backward
Indexing
Slice Generates
L[4: ] [13, 15, 17, 19, 23, 25]
L[ : 3] [2,7,9]
L[2: 5] [9,10, 13]
L[4: : 2] [13, 17, 23]
L[2 : 7 : 2] [9, 13, 17]
L[ : : -1] [25, 23, 19, 17, 15, 13, 10, 9, 7, 2]
L[ : : -2] [25, 19, 15, 10, 7]
L[6 : 1: -2] [17, 13, 9]
L[-8 : 8 ] [9, 10, 13, 15, 17, 19]
L[3 : -2 : 2] [10, 15, 19]
L[6 : -9 : -2] [17, 13, 9]
OUTPUT :
Enter an element to search:2
2 is present in [1, 2, 3, 4, 5]
OUTPUT :
Enter an element to search:20
20 is not present in [1, 2, 3, 4, 5]
12. Accessing Nested Lists
A list containing another list within it is known as nested list. For accessing nested list
member we can use two square brackets- the first showing the index in the outer list
and the next
showing the index for the inner list.
L=[1,2,[3,4,5], [6,7,8] ]
print('L[0]=', L[0])
print('L[2]=', L[2])
print('L[2][1]=',L[2][1])
print('L[3][2]=',L[3][2])
OUTPUT :
L[0]= 1
L[2]= [3, 4,
5] L[2][1]=
4
L[3][2]= 8
13. List Functions/methods
Worksheet -Lists
B) L1,L2 =[2,4],[2,4]
L3=list(L2)
L2[1]=5
Print(L3)
3)List can contain values of these types:
1. integers 2. floats3. lists 4. tuples 5. all of these
Which of the following will create an empty list?
1. L = () 2. L = list(0) 3. L = list( ) 4. L = List(empty)
Question 3
If L = [1, 2] then L * 2 will yield
1. [1, 2] * 2 2. [1, 2, 2] 3. [1, 1, 2, 2] 4. [1, 2, 1, 2]
Question 4
If L1 = [1, 3, 5] and L2 = [2, 4, 6] then L1 + L2 will yield
1. [1, 2, 3, 4, 5, 6] 2. [1, 3, 5, 2, 4, 6] 3. [3, 7, 11] 4. [1, 3, 5, [2, 4, 6]]
Given a list L= [10, 20, 30, 40, 50, 60, 70], what would L[1 : 4] return?
1. [10, 20, 30, 40] 2. [20, 30, 40, 50] 3. [20, 30, 40] 4. [30, 40, 50]
Given a list L= [10, 20, 30, 40, 50, 60, 70], what would L[2 : -2] return?
1. [10, 20, 30, 40] 2. [20, 30, 40, 50] 3. [20, 30, 40] 4. [30, 40, 50]
Given a list L= [10, 20, 30, 40, 50, 60, 70], what would L[-4 : -1] return?
1. [20, 30, 40] 2. [30, 40, 50] 3. [40, 50, 60] 4. [50, 60, 70]
Given a list L= [10, 20, 30, 40, 50, 60, 70], what would L[-3 : 99] return?
1. [20, 30, 40] 2. [30, 40, 50] 3. [40, 50, 60] 4. [50, 60, 70]
Question 9
What is the output when we execute list("hello")?
1. ['h', 'e', 'l', 'l', 'o'] 2. ['hello'] 3. ['llo'] 4. ['olleh']
What is printed by the Python code?
print(list(range(3)))
1. [0, 1, 2, 3] 2. [1, 2, 3] 3. [0, 1, 2] 4. 0, 1, 2
12 Start with the list [8, 9, 10]. Do the following using list functions:
1. Set the second entry (index 1) to 17
2. Add 4, 5 and 6 to the end of the list
3. Remove the first entry from the list
4. Sort the list
5. Double the list
6. Insert 25 at index 3
13)W.A.P in python to ask the user to enter a list containing numbers between 1 and
12. Then
replace all of the entries in the list that are greater than 10 with 10.