Lists in Python - Notes
Lists in Python - Notes
The data type list is an ordered sequence which is mutable and made up of
one or more elements. Unlike a string which consists of only characters, a list
can have elements of different data types, such as integer, float, string, tuple
or even another list.
Lists are Mutable
In Python, lists are mutable. It means that the contents of the list can be
changed after it has been created.
List Operations
a. Concatenation (+)
list1 = [1,3,5,7,9]
list2 = [2,4,6,8,10]
list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
b. Repetition(*)
list1 = ['Hello']
list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
c. Membership
the membership operators in checks if
the element is present in the list and returns True, else’
returns False.
list1 = ['Red','Green','Blue']
'Green' in list1
True
'Cyan' in list1
False
d. Slicing
List1=[1,2,3,4,5,6,7,8,9,10]
print(list1[::])
[1,2,3,4,5,6,7,8,9,10]
Print(list1[:])
[1,2,3,4,5,6,7,8,9,10]
print( list1[2:])
[3, 4, 5, 6,7,8,9,10]
Print(list1[:2])
[1,2]
Print( list1[::3])
[1, 4, 7, 10]
List Methods and Built-in Functions
Nested Lists
When a list appears as an element of another list, it is
called a nested list.
Example 9.2
>>> list1 = [1,2,'a','c',[6,7,8],4,9]
#fifth element of list is also a list
>>> list1[4]
[6, 7, 8]
To access the element of the nested list of list1, we have
to specify two indices list1[i][j]. The first index i
will take us to the desired nested list and second index
j will take us to the desired element in that nested list.
Ex:list1[4][2] will give 8
Copying Lists
list1 = [1,2,3]
>>> list2 = list1
The statement list2 = list1 does not create a
new list., it just makes list1 and list2 refer
to the same list object. list2 a becomes an
alias of list1. Therefore, any changes made to either of
them will be reflected in the other list.
>>> list1.append(10)
>>> list1
[1, 2, 3, 10]
>>> list2
[1, 2, 3, 10]
To copy the list we have 3 other methods
Method 1
By slicing
1. newList = oldList[:]
Method 2
We can use the built-in function list() as follows:-
newList = list(oldList)
Method 3
We can use the copy () function as follows:
import copy #import the library copy
#use copy()function of library copy
newList = copy.copy(oldList)
del statement
To delete the elements from a list using index
del list1[2]- delete the element at index 2
del list[:2]- delete the elements till the index number 2(excluding index 2]
del list[2:]- delete the elements from index 2(including index 2)
del list1[:]- delete the entire list
dele] list1[::]- delete the entire list