Professional Documents
Culture Documents
The data type list is an ordered sequence which is mutable and made up of one or
more items or elements.
Unlike string which consists of only characters, list can have elements of different
data types such as integer, float, string, tuple or even list.
Elements of a list are enclosed in square brackets and are separated by comma.
For Example:
In Python, lists are mutable means the contents of the list can be changed after it
has been created.
Python allows us to join two or more lists using concatenation operator (+).
#index that is too big is truncated down to the end of the list
>>> list1[2:20]
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
#negative indexes
>>> list1[-6:-2] #elements at index -6,-5,-4,-3 are sliced
['Green','Blue','Cyan','Magenta']
OUTPUT:
Red
Green
Blue
Yellow
Black
OUTPUT:
Red
Green
Blue
Yellow
Black
Method Description Example
len() Returns the length of the list passed as the >>> list1 = [10,20,30,40,50]
argument >>> len(list1)
5
list() Creates an empty list if no argument is passed >>> list1 = list()
Creates a list if sequence is passed as >>> list1
argument []
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']
append() Appends a single element passed as argument >>> list1 = [10,20,30,40]
at the end of the list >>> list1.append(50)
The single element can also be a list >>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]
Method Description Example
extend() Appends each element of the list passed as >>> list1 = [10,20,30]
argument to the end of the given list >>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
insert() insert(index, element) - inserts an element at a >>> list1 = [10,20,30,40,50]
particular index in the list >>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]
count() Returns the number of times a given element >>> list1=[10,20,30,10,40,10]
appears in the list. >>> list1.count(10)
3
>>> list1.count(90)
0
Method Description Example
index() Returns index of first occurrence of the >>> list1=[10,20,30,20,40,10]
element in the list. If the element is not >>> list1.index(20)
present, ValueError is shown 1
>>> list1.index(90)
ValueError: 90 is not in list
remove() Removes the given element from the list. If >>> list1=[10,20,30,40,50,30]
the element is present multiple times, only the >>> list1.remove(30)
first occurrence is removed. If the element is >>> list1
not present, then ValueError is shown. [10, 20, 40, 50, 30, 60]
>>> list1.remove(90)
ValueError:list.remove(x):x
not in list
Method Description Example
pop() Returns and removes the element whose >>> list1 = [10,20,30,40,50,60]
index is passed as parameter to this function. >>> list1.pop(3)
If no parameter is given then it returns and 40
removes the last element of the list. >>> list1
[10, 20, 30, 50, 60]
>>> list1=[10,20,30,40,50,60]
>>> list1.pop()
60
>>> list1
[10, 20, 30, 40, 50]
Method Description Example
reverse() Reverses the order of elements in the given >>> list1 = [34,66,12,89,28,99]
list. >>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
>>> list1= [ 'Tiger' ,'Zebra' ,
'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion',
'Zebra', 'Tiger']
>>> list1=[34,12,63,39,92,44]
min() Returns minimum element of the list >>> min(list1)
max() Returns maximum element of the list 12
sum() Returns sum of the elements of the list >>> max(list1)
92
>>> sum(list1)
284
Method Description Example
sort() Sorts the elements of the given list in place >>>list1 =
['Tiger','Zebra','Lion', 'Cat',
'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion',
'Tiger', 'Zebra']
>>> list1=[34,66,12,89,28,99]
>>> list1.sort(reverse=True)
>>>list1
[99,89,66,34,28,12]
sorted() sorted() is a function which takes list as >>>list1 =[23,45,11,67,85,56]
parameter. It leaves the argument unchanged >>> list2 = sorted(list1)
and instead creates and returns a list consisting >>> list1
of the same elements arranged in sorted order. [23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]
NESTED LISTS
To access the element of the nested list of list1, we have to specify two
indices list1[i][j].
The first index will take us to the desired nested list and second will take us
to the desired element in that nested list.
>>> list1[4][1]
#index i gives the fifth element of list1 which is a list
#index j gives the second element in the nested list
COPYING LISTS
Given a list list1. The simplest way to make a copy of the list is to assign it to
another list.
>>> list1 = [1,2,3]
>>> list2 = list1
>>> list1
[1, 2, 3]
>>> list2
[1, 2, 3]
The statement list2 = list1 does not create a new list. Rather it just makes list1 and
list2 refer to the same list object. list2 actually 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]
>>> lsit2
[1, 2, 3, 10]
COPYING LISTS
newList = oldList[:]
For Example:
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
For Example:
>>> import copy
>>> list1 = [1,2,3,4,5]
>>> list2 = copy.copy(list1)
>>> list2
[1, 2, 3, 4, 5]
LIST AS ARGUMENTS TO FUNCTION
(a) Elements of the original list may be changed, i.e. changes made to the list in the
function are reflected back in the calling function.
def increment(list2):
for i in range(0,len(list2)):
list2[i] += 5
print('Reference of list Inside Function',id(list2))
#end of function
LIST AS ARGUMENTS TO FUNCTION
OUTPUT:
Reference of list in Main 2846531232008
The list before the function call
[10, 20, 30, 40, 50]
Reference of list Inside Function 2846531232008
The list after the function call
[15, 25, 35, 45, 55]
(b) If the list is assigned a new value inside the function then a new list object is
declared and it becomes the local copy of the function. Any changes made inside
the local copy of the function are not reflected back to the calling function.
def increment(list2):
print("\nID of list inside function before assignment:",id(list2))
list2 = [15,25,35,45,55]
print("ID of list changes inside function after assignment:",id(list2))
print("The list inside the function after assignment is:")
print(list2)
#end of function
LIST AS ARGUMENTS TO FUNCTION
list1 = [10,20,30,40,50] #Create a list
print("ID of list before function call:",id(list1))
print("The list before function call:")
print(list1)
increment(list1) #list1 passed as parameter to function
print('\nID of list after function call:', id(list1))
print("The list after the function call:")
print(list1)
OUTPUT:
ID of list before function call: 2116271067656
The list before function call:
[10, 20, 30, 40, 50]
Continued:
Output
Initially, f=0
s=1
If input n=6
next=f+s f=s s=next for x in
range(2,n)
1 1 1 2
2 1 2 3
3 2 3 4
5 3 5 5
fib=next
i.e. 6th number in the series is 5.
Dry Run
Initially, fact=1,
If input n=6
fact= 120
i.e. factorial of 5 is 120.
Write a function that takes a list of values as input
parameters and returns another list without any
duplicates.
def mylist(list1):
newlist=[]
for i in list1:
if i not in newlist:
newlist.append( i )
print(newlist)
list1=[1,6,2,3,4,5,7,7,8,9,1,2]
print("list of the elements having duplicate items")
print(list1)
print("list of the elements after removing duplicate items")
mylist(list1)
Program With Output-
def myfunc(a):
print("the list given to the function is",a)
c=[]
for i in a:
print(i)
# if the element of list a is not in list c, then app
end that element in list c
print("List c as of now",c)
if i not in c:
c.append(i)
print("List c after adding the element:", c)
print("List formed by the function is", c)
return(c)
a=[2,3,4,2,4]
b=[]
b=myfunc(a)
print("List returned from the function is", b)
the list given to the function is [2, 3, 4, 2, 4]
2 List c as of now [] List c after adding the
element: [2] 3 List c as of now [2] List c after
adding the element: [2, 3] 4 List c as of now [2,
3] List c after adding the element: [2, 3, 4] 2
List c as of now [2, 3, 4] 4 List c as of now [2,
3, 4] List formed by the function is [2, 3, 4]
List returned from the function is [2, 3, 4]
List1= 1 6 2 3 4 5 7 7 8 9 1 2
0 true 1
1 true 6
2 true 2
3 true 3
4 true 4
5 true 5
6 true 7
7 False -
8 true 8
9 true 9
10 False -
11 False -
Write a function that takes a list of numbers as
input from user and produces the corresponding
cummulative list where each element in the list at
index I is the sum of elements at index j<=i.
def cumulative():
mylist=[]
num=int(input("enter the length of a list"))
print("enter numbers")
for i in range(num):
data=int(input())
mylist.append(data)
cu_list=[]
sum=0;
for item in range(0,len(mylist)):
sum+=mylist[item]
cu_list.append(sum)
print("list=",mylist)
print("cumulative sum of list ",cu_list)
cumulative()
Program With Output
Dry Run-
Mylist= 10 20 30 15 25
1 10+20=30 30
2 30+30=60 60
3 60+15=75 75
4 75+25=100 100
List operations
Write a menu driven program to perform various list operations such as:
Append an element, insert an element, append a list to the given list, modify an existing
element, delete an existing element by its position, delete an existing element by its value,
sort the list in ascending order, sort the list in descending order and display the list.
SORTED IN DESCENDING
ORDER
DRY RUN
Input=12,13,14 operations i=0 i=1 i=2
def computeAverage(list1,n):
total = 0 #initialize total
for marks in list1:
total = total + marks #add marks to total
average = total / n
return average