Python Lists: Creation, Access, and Operations
Python Lists: Creation, Access, and Operations
LISTS
AISMV---XI---IP---POOJA THAKUR
List data type
Creating Lists
Replication in Lists
Slicing in Lists
AISMV---XI---IP---POOJA THAKUR
Sequences in Python
➢Strings ex: “123”
➢Lists ex: [1,2,3]
➢Tuples ex: (1,2,3)
➢Dictionaries ex{‘a’:1, ‘b’:2, ‘c’:3}
AISMV---XI---IP---POOJA THAKUR
LISTS
List is a collection of values or an ordered
sequence of values and items.
The items in a list can be of any type: strings,
integers, float or even list.
AISMV---XI---IP---POOJA THAKUR
LIST
• A M O S T V ER S ATI LE D ATA TY P E I N P Y TH O N.
S Q U A R E BR A C K ETS [ ] .
• I TEM S N EED N O T TO BE O F S A M E TY P E. ( U N LI KE
S TR I N G S)
• LI S TS A R E M U TA BLE. ( U N LI KE S TR I N G S)
AISMV---XI---IP---POOJA THAKUR
CREATING LISTS
To Create a list, you separate the elements with a comma and enclose them with a bracket [ ].
The Syntax is :
<name of list>=[<value>,<value>,value>]
For example:
>>> list1=[67,82,98,78,87] # a numeric list
>>> list 2=[‘pen’, ’pencil’, ’scale’, ’eraser’, ‘marker’] # a character/string list
>>> list3=[‘A V Raman’, 35, ‘Scientist’ , 87650.00] # a list with multiple type values
>>> list 4=[] # an empty list
>>>list5=[1,2,[10,20,30],4,5] # Nested list
AISMV---XI---IP---POOJA THAKUR
CREATING LISTS
Creating list from existing sequence using list()
The Syntax is :
<name of list>=list(sequence/string)
For example:
>>> list1=list(‘computer’) # convert a string to list
>>> list 1
[‘c’ , ‘o’ , ‘m’ , ‘p, ‘u’ , ‘t’ , ‘e’ , ‘r’ ]
>>> list2=list() # create an empty list
>>>list3=[10,20,30,40,50]
>>>list4=list3
>>>list4 output-> [10,20,30,40,50]
AISMV---XI---IP---POOJA THAKUR
Accessing List Elements
➢We can access individual list elements using indexing and a range of elements using slicing.
➢Python indexes the list elements from left to right (forward indexing), the first element has an
index 0, in backward indexing, the indexing starts from -1 (right to left)
➢Individual elements in a list can be accessed by specifying the list name followed by a number
in square brackets [].
FORWARD INDEXING
BACKWARD INDEXING
AISMV---XI---IP---POOJA THAKUR
Accessing List Elements
Each element in the list can be accessed using index.
Syntax:
<listname>[<index>]
Example: Consider the list L1
L1=[1,2,3,4,5,6,7,8,9,10]
L1[0] → return 1
L1[2+1] → return 4 #access the 3rd index element
L1[9-2] → return 8 # access the 7th index element
L1[-2] → return 9
AISMV---XI---IP---POOJA THAKUR
Lists are mutable
➢When the bracket operator appears on the left side of an
assignment, a value is assigned to the element of a list .
Note: A list is a relationship between indices and elements. This relationship is called
Mapping. Each index “maps to” one of the elements.
AISMV---XI---IP---POOJA THAKUR
Lists are Mutable
Output:
AISMV---XI---IP---POOJA THAKUR
len(list)
3
L=[1,2,3]
print(len(L))
+ (concatenation)
Basic List
Operations L=[1,2,3]
L2=[3,4,5]
and Functions [1, 2, 3, 3, 4, 5]
print(L+L2)
* (repetition)
L=[1,2,3]
print(L*3) [1, 2, 3, 1, 2, 3, 1, 2, 3]
AISMV---XI---IP---POOJA THAKUR
len()
➢len() returns the length of the list or the count of the
elements in a list.
➢Example:
numbers = [24 , 35 , 78]
len(numbers) # return 3
L=[“riya”,”adit”, “siya”, “rajat”, “Aditya”]
len(L) ?
AISMV---XI---IP---POOJA THAKUR
Concatenation
L=[“Aditya”, “Rajat”]
L1=[“Divya”, “Shivam”]
Print(L+L1) # Return ['Aditya', 'Rajat', 'Divya', 'Shivam']
L2= [1,2,3]
L3=L1+L2 # Return ['Divya', 'Shivam', 1, 2, 3]
L2+”Hello” # return TypeError: can only concatenate list (not "str") to list
L2+2 # return TypeError: can only concatenate list (not "int") to list
AISMV---XI---IP---POOJA THAKUR
Replication
L=[“Aditya”, “Rajat”]
L2= [1,2,3]
AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
Consider the list1 and list2 given below:
list1=[67,82,98,92,78,87]
<listname>[start:stop:step]
0 1 2 3 4
Red Yellow Blue Green white
-5 -4 -3 -2 -1
List1=["red","yellow","blue","green","white"]
List1[2:6] ['blue', 'green', 'white']
List1[2:20]
['blue', 'green', 'white']
List1[5:2]
[] Empty list
List1[:5]
[‘red’, ‘yellow’,‘blue', 'green', 'white']
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4
Red Yellow Blue Green white
-5 -4 -3 -2 -1
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4 5 6 7 8 9
L= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(l[-7::-2])
print(l[9:0:-2])
Output:
[2,8,20,18]
[18, 20, 8, 2, 5]
[18, 20, 8, 2, 5]
l= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(l[-len(l):-1:2])
Output:
[2,8,20,18]
[18, 20, 8, 2, 5]
[18, 20, 8, 2, 5]
10
20
30
40
50
60
ITERATING / TRAVERSING THROUGH LIST
Remember!!
else of for loop is only
executed after successful
Output
completion of the loop
ITERATING / TRAVERSING THROUGH LIST
Write a program to print the elements of the list L using len() and range()
L=['q','w','e','r','t','y']
length=len(L)
print("The reverse of the list is: ",end=" ")
for a in range(-1,-length-1,-1):
print(L[a],end=" ")
Output:
The reverse of the list is: y t r e w q
ITERATING / TRAVERSING THROUGH LIST
Program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in separate
lines along with element’s both indexes (positive & negative)
L=['q','w','e','r','t','y']
length=len(L)
for a in range(length):
print("At indexes", a, "and" , (a-length), "element:", L[a])
Output:
At indexes 0 and -6 element: q
At indexes 1 and -5 element: w
At indexes 2 and -4 element: e
At indexes 3 and -3 element: r
At indexes 4 and -2 element: t
At indexes 5 and -1 element: y
Which of the following commands will create
a list?
a) list1 = list()
b) list1 = []
c) list1 = list([1, 2, 3])
d) all of the mentioned
Recap
What is the output when we execute
list(“hello”)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]
AISMV---XI---IP---POOJA THAKUR
Suppose list1 is [2445,133,12454,123], what
is list1[:1]?
a) 2445
b) 133
c) 12454
Recap d) 123
What is the output when we execute
l=list(“hello”). print(l[::-1)?
a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
b) [‘hello’]
c) [‘llo’]
d) [‘olleh’]
AISMV---XI---IP---POOJA THAKUR
Difference between l=[‘hello’] and
Recap l=[‘h’,’e’,’l’,’l’,’o’]
AISMV---XI---IP---POOJA THAKUR
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
Consider the list1 and list2 given below:
list1=[67,82,98,92,78,87]
<listname>[start:stop:step]
0 1 2 3 4
Red Yellow Blue Green white
-5 -4 -3 -2 -1
List1=["red","yellow","blue","green","white"]
List1[2:6] ['blue', 'green', 'white']
List1[2:20] ['blue', 'green', 'white']
List1[5:2] [] Empty list
List1[:5]
[‘red’, ‘yellow’,‘blue', 'green', 'white']
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4
Red Yellow Blue Green white
-5 -4 -3 -2 -1
AISMV---XI---IP---POOJA THAKUR
Slicing List Elements
0 1 2 3 4 5 6 7 8 9
L= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(l[-7::-2])
print(l[9:0:-2])
Output:
[2,5]
[18, 20, 8, 2, 5]
[18, 20, 8, 2, 5]
l= 4 5 1 2 9 8 15 20 22 18
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(l[-len(l):-1:2])
10
20
30
40
50
60
ITERATING / TRAVERSING THROUGH LIST
Remember!!
else of for loop is only
executed after successful
Output
completion of the loop
ITERATING / TRAVERSING THROUGH LIST
Write a program to print the elements of the list L using len() and range()
L=['q','w','e','r','t','y']
length=len(L)
print("The reverse of the list is: ",end=" ")
for a in range(-1,-length-1,-1):
print(L[a],end=" ")
Output:
The reverse of the list is: y t r e w q
ITERATING / TRAVERSING THROUGH LIST
Program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in separate
lines along with element’s both indexes (positive & negative)
L=['q','w','e','r','t','y']
length=len(L)
for a in range(length):
print("At indexes", a, "and" , (a-length), "element:", L[a])
Output:
At indexes 0 and -6 element: q
At indexes 1 and -5 element: w
At indexes 2 and -4 element: e
At indexes 3 and -3 element: r
At indexes 4 and -2 element: t
At indexes 5 and -1 element: y
Write a program to display every
alternate element from the list L
given below:
Practice
Question L=[10,20,30,40,50,60,70,80,90,100]
L=[10,20,30,40,50,60,70,80,90,100]
l=len(L)
for i in range(0,l,2):
print(L[i])
A nested list is created by placing a comma-separated
sequence of sublists.
Nested lists
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h’]
L[3:4][0][1]
L[3:4][0][1][2]
Nested List
Example:
0 1 2 3 4 5 6 7
L=['These','are’, 'a’, ['few','words'],'that','we','will','use’]
-8 -7 -6 -5 -4 -3 -2 -1
“few” in L False
Recap A) H
B) n
C) a
D)Dia
COMPARING LIST
Python gives the final result of non equality comparisons as soon as it gets a result in
terms of True/False. If corresponding elements are equal it goes on to next element,
and so on until it finds elements that differ.
True
False
False
True
TypeError: '>=' not supported between instances of 'list' and 'int'
False
MAKING TRUE COPY OF LIST
L1=[1,2,3,4,5]
L2=L1 # both L1 and L2 are pointing to the same memory location
L2[0]=15
print(L1) # The first element at 0 index will be now 15 in both the lists L1 and L2
We can create a true copy of the list by any of the following methods:
L2=L1.copy()
L2[0]+=10
L2[-1]+=10
print(L1)
print(L2)
MAKING DEEP COPY OF LIST
L=['These','are','a',['few','words'],'that','we','will','use’]
L2=L.copy()
L[3][0]=10
L2
L3[3][0]="new"
L3
L
Lists and strings are interchangeable
We can change lists to string or vice versa by using list() and str() function and hence respective functions can
be used.
>>>L1=list(“hello”) # string to list
>>>L1
[‘h’, ’e’, ‘l’, ‘l’, ‘o’ ]
>>>t=(‘w’, ’e’, ’r’, ’t’, ’y’) # Tuple to list
>>>L2=list(t)
>>>L2
[ ‘w’, ’e’, ’r’, ’t’, ’y’ ]
>>> S=str(L1) # Lists to string
What is the output of the following python code?
l=[None]*10
print(len(l))
Recap A) 10
B)0
C) None
D) Syntax error
List Functions
L=[1,2,3,None]
Print(len(L)) ?
index()
This function returns the index of first matched item from the list
Syntax:
List.index(<item>)
Example:
Num=[23,54,34,44,35,66,27,88,69,54]
Num.index(54) # return 1
Num.append(55,10)
append()
append() is equivalent to a[len(a):] = [x].
Example 1
l=[4]
l.append(5) Output:
print(l)
[4, 5]
[4, 5, [6]]
l.append([6])
[4, 5, [6], (4, 5)]
print(l)
l.append((4,5))
print(l)
extend()
The extend() method is used for adding multiple elements (given in the form of a list) to a list.
Syntax:
List.extend(<list>) # takes exactly one element (a list type) and returns no value
Example:
L1=[1,2,3]
L2=[4,5]
L1.extend(L2)
print(L1)
print(L2)
L3=L1.extend(L2) # L3 will return None as extend() does not return anything
print(L3)
List Methods
(extend)
list.extend(iterable) -Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] =iterable.
Example 1:
L=[1,2]
L.extend([3,4])
print(L)
L.extend(‘bye’) Output:
print(L) [1, 2, 3, 4]
L.extend((9,10)) [1, 2, 3, 4, 'b', 'y', 'e']
print(L) [1, 2, 3, 4, 'b', 'y', 'e', 9, 10]
L.extend(4) Error
print(L)
Append() Extend()
Append adds one element Extend adds a sequence to
to the list the list
Difference Element can be simple or Element has to be
between sequential data type sequence only
extend and Element will be added as a Element will be split into
single element each individual item
append
Eg Eg
L=[1] L=[1]
L.append([3,4]) L.extend([3,4])
print(L) #[1,[3,4]] print(L) #[1,3,4]
print(len(l)) #2 Print(len(L)) #3
insert()
The append and extend method inserts at the end of the list
The insert() inserts the element at the specified index in a list
The element can be added anywhere in between the list.
Syntax:
List.insert(<index>,<item>) # takes 2 arguments and returns no values
Num=[23,54,34,44,35,66,27,88,69,54]
Num.insert(0,5)
print(Num)
Num.insert(15,5) # when the index is beyond the last index, item in added to the end of the list
Num.insert(-1,5) # Negative index can be specified to insert.
Num.insert(-15,5) # negative index is less than the first element index then element is added at beginning
List Methods -list.insert()
Insert an item at a given position.
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Practice Question
Write a program to input a string and convert it to a list. Print the index numbers of the vowels
present in the list.
Raises ValueError incase value does Raises IndexError incase index does
not exist not exist
L=[1,2,3,None]
Print(len(L)) ?
index()
This function returns the index of first matched item from the list
Syntax:
List.index(<item>)
Example:
Num=[23,54,34,44,35,66,27,88,69,54]
Num.index(54) # return 1
Num.append(55,10)
append()
append() is equivalent to a[len(a):] = [x].
Example 1
l=[4]
l.append(5) Output:
print(l)
[4, 5]
[4, 5, [6]]
l.append([6])
[4, 5, [6], (4, 5)]
print(l)
l.append((4,5))
print(l)
extend()
The extend() method is used for adding multiple elements (given in the form of a list) to a list.
Syntax:
List.extend(<list>) # takes exactly one element (a list type) and returns no value
Example:
L1=[1,2,3]
L2=[4,5]
L1.extend(L2)
print(L1)
print(L2)
L3=L1.extend(L2) # L3 will return None as extend() does not return anything
print(L3)
List Methods
(extend)
list.extend(iterable) -Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] =iterable.
Example 1:
L=[1,2]
L.extend([3,4])
print(L)
L.extend(‘bye’) Output:
print(L) [1, 2, 3, 4]
L.extend((9,10)) [1, 2, 3, 4, 'b', 'y', 'e']
print(L) [1, 2, 3, 4, 'b', 'y', 'e', 9, 10]
L.extend(4) Error
print(L)
Append() Extend()
Append adds one element Extend adds a sequence to
to the list the list
Difference Element can be simple or Element has to be
between sequential data type sequence only
extend and Element will be added as a Element will be split into
single element each individual item
append
Eg Eg
L=[1] L=[1]
L.append([3,4]) L.extend([3,4])
print(L) #[1,[3,4]] print(L) #[1,3,4]
print(len(l)) #2 Print(len(L)) #3
insert()
The append and extend method inserts at the end of the list
The insert() inserts the element at the specified index in a list
The element can be added anywhere in between the list.
Syntax:
List.insert(<index>,<item>) # takes 2 arguments and returns no values
Num=[23,54,34,44,35,66,27,88,69,54]
Num.insert(0,5)
print(Num)
Num.insert(15,5) # when the index is beyond the last index, item in added to the end of the list
Num.insert(-1,5) # Negative index can be specified to insert.
Num.insert(-15,5) # negative index is less than the first element index then element is added at beginning
List Methods -list.insert()
Insert an item at a given position.
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Practice Question
Write a program to input a string and convert it to a list. Print the index numbers of the vowels
present in the list.
Raises ValueError incase value does Raises IndexError incase index does
not exist not exist
Answer: len()
Q2. Which of the following can add only one value to a list?
A)append()
RECAP B) extend()
C)add()
D)none of these
Answer: append()
Q3. Which of the following can delete an element from a list
if the value is given?
A) del()
RECAP B) remove()
C)pop()
D)all of these
Answer: remove()
Q4. Which of the following searches for an element in a list
and returns its index?
A) search()
RECAP B) find()
C)index()
D)lsearch()
Answer: index()
Recap
Predict the output of the code given below:
L=['p','w','r','d','a']
L.remove('r’) # no output
print(L)
print(L.pop())
del L[1] No output
print(L)
Recap
Predict the output of the code given below:
L1=[10,20,30,40]
L1.clear()
print(L1)
Empty List is printed
L1=[10,20,30,40]
del(L1)
print(L1)
min()
Returns minimum or smallest element of the list
Syntax:
min(<listname>)
List1=[14,23,45,65,34,12,25,67] Return : 12
min(List1)
max(List1)
List1=[14,23,45,65,34,12,25,67]
sum(List1)
Return : 285
L=["12",'Arjun',"_@_","jiya","94"]
sum(L)
The str class contains the split method, which is useful for
splitting items in a string into a list. For example, the
following statement:
L=[]
n=int(input("enter number of elements"))
for i in range(n):
x=int(input("enter list element"))
L.append(x)
for j in L:
if j%5==0:
print(j)
Practice Question
WAP to count the frequency of a given element in a list of numbers.
Sample output
L=eval(input("Enter List elements"))
print("original list: ", L)
x=int(input("enter item to search:"))
count=0
for i in L:
if i==x:
count+=1
print("The element ",x, "occurs ",count, " times")
Practice Question
WAP to find the minimum element from a list of element along with its index in the list