0% found this document useful (0 votes)
34 views86 pages

L6 Lists

Uploaded by

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

L6 Lists

Uploaded by

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

LESSON 6

LIST MANIPULATION
Introduction of list sequence
datatype
• Python lists are containers that are used to store a list of values of any
type.
• Python lists are mutable means the element of a list can be modified.
• So python will not create a new list when changes are made in lists.
NOTE: mutable means memory location will not change even if list’s
elements are edited i.e. values can change]
Creating list
• Lists are created using [ ] square brackets.
• Lists can store a sequence of values of any type or mixed
datatypes. Lists data is separated by comma(,)
• EGs
L1=[] #this is empty list
L1=[1,2,3] # list of integers
L1=[‘a’, ‘b’, ‘c’] #list of strings
L1=[5.5,4.4,3,3] #list of floats
L1=[1, ‘Superman’, 99.4] #mixed list
Creating list
• EG1: empty list is []. The empty list’s truth value will be
false. Creating an empty list:
L1=[]
print(L1)
L2=list()
print(L2)
print(L1==True) o/p False
B’coz truth value of L1 is False
• Long lists
L1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Creating list
• EG2: Long lists- A list can contain many elements i.e. no
limit.
L1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Creating and accessing list
• EG3: Nested lists- A list can have an elements in it, which
itself is a list.
PROGRAM1:
L1=[1, ‘Ram’, [30,40,50], ‘aundh’]
L1[0] is 1 L1[1] is ‘Ram’
L1[2] is [30,40,50] L1[3] is ‘aundh’

PROGRAM2:
L=[30,40,50]
Stud1=[1, ‘Ram’, L, ‘aundh’]
#Here L is another list and part of list Stud1
Creating lists from existing sequence
• Built-in list type object is used to create lists from
sequence. Sequence object can be of any kind i.e. string,
tuples or lists itself.
• If another list is pass as an object a copy of the list is
formed.
• Syntax: L1=list(<sequence>) #list() is function.
Here, “hello” is string sequence converted to list.

Here, t is tuple sequence converted to list.


Inputting List from user
• Inputting data without space or comma

• Space is also a element of list

• Comma is a element of list


• input () is used to input string data so all data is
converted to string and stored as list element.
• If typed following code also gives an error msg.
The eval() function
• The eval() function of python can used to evaluate and return the result
of an expression given as string.
EG1:
eval(‘5’+ ‘8’) o/p 58 #first it concatenates
eval(‘5+1’) o/p 6 #will calculate and then converts to int

Here y variable is of int type and z’s value is inputting from user and also of int type
Use [] square brackets for lists type data and () round brackets for tuple type data.
Comma is used as separator.
Accessing list
• List is compound datatype.
• List data can be change i.e. mutable (means can add/delete/modify
element(s). Accessing list is somewhat similar to string.
• List data is separated by comma(,)
• List data is represented in square brackets [ ].
• Eg1 a=[1, 2, 3, 4, 5]
b=[‘a’, ‘e’, ‘I’, ‘o’, ‘u’]
c=[‘Donna’, 102, 87.5]
0 1 2 {each item has index no. ,starts with 0}
Indexes in Lists

• Lists also have index no of each element i.e. forward index nos and backward
index nos.
Accessing elements of List
Understanding more on lists
len() function returns the no. of elements in list

Concatenation operator (+) will join two lists. Remember concat


operator has similar operands to operate upon.
Replication operator (*) will replicate or repeats the list’s elements

Membership operators(in and not in) returns True/False is an element is


present in the list or not
L2=[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
id() function to find or return the location no of an object.
Study the following eg. L1 list’s id, before and after changing the
element.
Difference between list and string
Lists Strings
1) Lists are mutable i.e. 1) Strings are immutable i.e. un-
editable/changeable. editable/unchangeable.
2) L1=[1,2, ‘a’, ‘b’] 2) S=‘12ab’
L1[0]=45 S[0]=45
print(L1) #ERROR cannot the value of str
[45,2, ‘a’, ‘b’] type
3) Lists allows to change 3) String cannot change
individual element. individual element.
Comparison between Lists and
String
Lists Strings
1. L1=[ ‘a’, ‘e’, ‘i’, ‘o’, ‘u’] 1. S1=‘aeiou’
L1[0] o/p ‘a’ S1[0] o/p ‘a’
len(L1) o/p 5 len(S1) o/p 5
id(L1) id(S1)
-6 -5 -4 -3 -2 -1
-3 -2 -1 backward index S2=
a b b c c d
0 1 2 3 4 5
2. L2=[‘ab’, ‘bc’, ‘cd’]
0 1 2 forward index
Comparison between Lists and
String
Lists Strings
3. Indexing & slicing
L1[0:2] S1[0:2]

4. Concatenation & replication


L1+L2 S1+S2
L1*2 S1*2

5. Membership operators ‘a’ in S1 o/p True


‘a’ in L1 o/p True ‘a’ not in S1 o/p False
‘a’ not in L1 o/p False
Traversing a list (means travel
across)
The for loop makes it easy to traverse or loop over the elements in a
list.
#Program1
L=['a','p','p','l','e’]
for a in L: 2nd iter a=‘p’
print(a)

#Program2
L=['a1','p2','p3','l4','e5']
for a in L:
print(a,end=“ “)
Using range( ) function
• Index elements can be accessed using range( ) and len( ) function.
#Program
L=['a','p','p','l','e']
le=len(L)
print(le)
for a in range(le):
print("at index",a, 'and',(a-le),'element:',L[a])
Comparing Lists (>, <, ==, !=)
• Python internally compares individual elements of lists and tuples in
lexicographical order.
• Means each corresponding element is compared to another list’s
element. For EG:

L1>L3 o/p False as 1 <4 compares 1st element of L1 with 1st element of L2

Similarly here 1< 4 so output is True


Find the o/p

[1,2,8,9] < [9,1] o/p True


[1,2,8,9] < [1,2,9,1] o/p True
[1,2,8,9] < [1,2,8,4] o/p False

L1,L2=[1,2,3],[‘1’,’2’,’3’]
L1==L2 o/p False
#string and int comparison always results to false
L1>L2 o/p ERROR cannot compare sting & int
List operations
• Joining lists i.e. + concatenation operator: will join 2 or more lists.
L1,L2,L3=[1,2],[10,20],[100,200]
LL3=L1+L2+L3
print(LL3) o/p [1,2,10,20,100,200]
L4=[‘a’, ‘b’]
L5=L1+L4
print(L5) o/p [1,2,’a’,’b’]

NOTE: for + operator both operands must be of list type else gives an error.
EG. L1+’a’
L1+10 ERROR
L1+complex no
• L2=L2+’abc’ gives error bcoz += is different from + for mutable iterable
types such as lists. Both operators have different rules in python.
• += is used with lists on the right side to iterable and it will add each
element of the iterable to the list.
• L2+=‘abc’ does not expand to L2 =L2+’abc’ for all types if L2 is list.
• Remember L2+=1 will give an ERROR as int is not iterable.
i=10
i+=1 OR i=i+1 11
Different memory location

L1=[1,3]
L1+=‘abc’ L1 [1,3, ‘a’, ‘b’,’c’]
Yet they r in same memory
L1=L1+’abc’ #ERROR
List operations
• Replication operator (*) : this operator is used to replicate a list specified
number of times.
L1=[1,2]
print(L1*3) o/p [1,2,1,2,1,2]
L4=[‘a’, ‘b’]
print(2*L4) o/p [‘a’,’b’,’a’,’b’]

NOTE: * operator requires a list and an integer as operands .


Slicing of lists
Extracting a part of list or subset means slicing.
<List_object>[Start_index: end_index-1:step_val]

Remember if 2nd parameter is larger then the


length will NOT give an error but will print till
end
Seq=lst[3:-3] endindex-1 (-3-1= -4)

-9 -8 -7 -6 -5 -4 -3 -2 -1
[10,12,14,20,22,24,30,32,34]
0 1 2 3 4 5 6 7 8
Seq [20,22,24]
Seq[0] ??20
Find output:
Lst=[2,4,6,8,10,12,14,16,18,20] Write a code to Print 18 to 10 ?
Lst[3:8]
Lst[-2:-7:-1]
Lst[1:8:1]
Lst[2:8:2] Lst[-2:3:-1]
Lst[0:10:3]
Lst[8:3:-1]
Lst[-8:-3]
Lst[-3:-8]
Lst[-3:-8:-1]

Lst[-3:3] ??
Lst[-3:3:1]
Lst[-3:3:-1]
Lst[0:11:3]
Lst[::4]
Lst[::-1]
Lst[::-3]
Lst=[2,4,6,8,10,12,14,16,18,20]
• Program 6.2 Page 190
Using slice for list modification
EG1:

[‘apple’, ’mango’, ’fruits’]


0 1 2
Remember endIndex-1

EG2:
• It gave error b’coz 55 is integer and not a iterable object

L1[0:1]=(55,) #taking tuple as replacing object


o/p [55, ‘5’, ‘z’, ‘fruits’]
Making True Copy of a list
• The true copy of the a list can be created using following:
1) By assigning old list to new list. (using = (equal to ) operator)
2) By using list() method
3) By using the copy() method
4) By sorting all elements of the list using list slice in its copy.
Making True Copy of a list using = equal to operator
Here, L2 is copy of L1. means both lists have same
elements.
Python will not make another list. But it will just
create a label pointing to same list of elements.

Check the id() function both L1 and L2 saved in same


memory location.
Note: if changes made in any of the lists will reflect
in other as L1 and L2 are referencing to same
memory location. Along with L1, list L2 also got
modified.
Making True Copy of a list using list() function

Note:
if list created using list() then the
new list remain unchanged and also
refer to different memory location.
Means both lists work independently.

Here, when changes made in L1 are


not reflected in L3
Making True Copy of a list using copy() function
• NOTE: list() and copy() functions are used for
copying a list but these are two different
functions.
list() function type casts into a list type.

copy() creates a copy of list.


Syntax: <new_Lst> = <old_list>.copy()
Program
Given a list L=[11,22,33,44,55]
WAP to create a copy of the list L and add 10 to its first and last
element. Then display both lists.
EG. 6.3 Page 192
Making True Copy of a list using slice
Copying and storing all elements of list using slice.
<newList>=<oldList>[start_index:end_Index-1:step_val]
WAP to make copy of list and add 10 to each element. Display both lists
lst=[17,24,15,30,27]
lst2=lst.copy()
for no in range(0,len(lst2)): for no in range(0,5)
lst2[no]+=10

print(lst)
print(lst2)
Using in operator
lst=[17,24,15,30,27]
lst2=lst.copy()
for no in lst2:
lst2=no+10
print(lst2,end=" ")
print(lst)
List functions and methods
• Every list object in python is actually an instance of List class. Various
operations can be performed on lists like appending (adding
items/elements), updating or deleting etc.
• Function can have fun_name, return type, parameter(s)/ argument(s)
• Function Prototype:
int sum(int,int..)
• Syntax :
<List_Object_name>.<method_name>()
Lets study the all functions in detailed:
1. len() function
• Returns the length of its argument list, i.e. no. of elements in list.
• Syntax: len(<List_Object>)
EG:

Nested list or tuple


passed as argument.
2. list() function
• Returns a list created from the
passed argument. Argument
should be of sequence type (list,
tuple, string etc. or even
dictionary)
• When argument is dictionary then
only dictionary’s keys are element
of list. But when you want store
values as elements of list then
study given a below code:

• NOTE: dictionary.keys() will display


keys and dictionary.values() will
display values of dictionary
3. index() function
• Returns the index of of 1st matched element from the list.
• Syntax: <list_object>.index(<item/value>)
• EG:

• In spite of 10 repeating 2 times shows the index of 1st matching


element.
• Gives error message if Value/item not found.
4. append() function
• Adds the element/item to the end of the list. It takes exactly one
element and returns no value.
• Syntax: <List_object>.append(<item>)
• EG1

• L1 and L2 are lists. Here L2 is added to L1 using append method.


4. append() function contd…
• EG2

• Adding string and tuple using append() function.


• EG3:

• In EG3 element 1 having index 0 is replaced with 100. updating the


element.
Eg:
5. extend() function
• This method is used for adding multiple elements (in list form). It means it
takes exactly one element as an argument of list type/sequence type i.e.
(tuple or string) and returns no value.
• Syntax: <List1_obj>.extend(<List2_obj>/<sequence>)
• EG:
• EG2:

• ERROR takes only one argument

• EG3: In EG3 extend()


parameter is
tuple and
String.
Difference between append() and
extend()
append() extend()
1. append() method adds one element 2. extend() add multiple elements at
at the end of list and takes value(either the end in the list/ sequence form. The
int/string or any sequence) as argument type is list
argument. • Eg: L1=[20,30,40]
• Eg: L1=[1,2,3] L1.extend((11,22,33))
L1.append(40) L1.extend(‘xyz’)
print(L1) o/p [1,2,3,40] print(L1)
o/p [20,30,40,11,22,33,’x’,’y’,’z’]

L1.extend(10) #ERROR int not iterable


Difference between append() and
extend()
append() extend()
2. After appending the length of list is 2. The length of list is increased by
increased by 1. the length of inserted lists/sequence.
• Eg: L1=[1,2,3] • Eg: L1=[20,30]
print(len(L1)) o/p 3 L2=[1,2]
L1.append(40) L1.extend(L2)
print(len(L1)) o/p 4 print(len(L1)) o/p 4
L1.append([55,77,99]) print(L1) o/p [20,30,1,2]
print(len(L1)) o/p 5 L1.extend(‘ab’)
print(L1) print(len(L1) o/p 6
print(L1)
[1,2,3,40,[55,77,99]]
o/p [20,30,1,2,’a’,’b’]
Difference between append() and
extend()
append() extend()
3. Eg: 3. Eg:
6. insert() function
• This function inserts an item at a given position. Takes 2 arguments and
returns no values.
• Syntax: <list_object>.insert(<index_position>, <itemValue>)

Inserted ‘x’ at 0th position.


• Inserting value using negative/backward index.

• If index is less than zero and not equal to any of the valid negative
indexes of the list, then adds the value in the beginning of the list.

• Similarly if index is positive and more then the length the adds the
value at last. Remember will NOT give an error
7. pop() function
• Removes/deletes the single item from the list. Takes one optional
argument and returns the deleted value.
• Syntax:<list_object>.pop(<index_No>)
Will delete the item as specified index.
OR
<list_object>.pop()
Will delete the last item if index is not specified.
Returns the deleted item
pop() takes only one argument
else gives an error.

Cannot pop() empty list.


#WAP to remove every 2nd element from list L and store it in new list
L=[1,2,3,4,5,6,7,8,9,10]
L1=[]
le=len(L)
#print(le)
for a in range(0,le,2):
L1.append(L[a])
print("Old list",L)
print("new list",L1)
8. remove() function
• Will remove an element form the list. Removes the first occurrence of
given item i.e. 1st matching element. It takes one argument i.e. element
of a list and returns no value.
• Syntax: <List_object>.remove(<value>)
• NOTE: report an error if there is no such item exists in list.
• EG:
• EG2: if try to remove two or more elements gives an error

• EG3: gives ERROR if item/value not found


• EG4: removes the first matching element.

• NOTE: the pop() takes index no. as argument and removes the item of
specified index, by returning the deleted item/element.
• Whereas, remove() take value/item as argument, removes the first
matching element and does not return any thing.
9. clear() function
• This method removes all items from the list; means list becomes empty
after this function. This function returns nothing.
• EG

• Means, list object exists but element does not.


10. del list[<startIndex>:<endIndex-1>:<stepval>]
OR
del (list[<startIndex>:<endIndex-1>:<stepval>])
• The above syntax is used to for deleting elements from a list.
• EG1: del <list_obj>[index]
is used to remove element at specified index
• EG2: del <list_obj>[Start_index: endIndex-1]
is used to remove element start index to (end index -1)

• EG2: del <list_obj>[Start_index: endIndex-1:step_val]


is used to remove element start index to (end index -1) by giving
step val
• Find the output given a list L=[0,1,2,3,4,5,6,7,8,9]

del L[::4] o/p [1, 2, 3, 5, 6, 7, 9]

del L[:]
Will make the list empty will remove
all elements from the list
del L[::1]

del L[::]
Deleting List object
• del <List_object> OR del(<List_object>)
Will delete the list object from the memory
NOTE: del and del() works same

• Also works with round brackets:


Mention the difference between clear()
and del() clear()
del
• 1. <list_obj>.clear() will make the
1. del<List_obj> will delete list along
list empty ie only items/values of
with its items.
list are removed. List_object
2. EG: L1=[1,2,3] remains in memory.
del L1 OR • 2. EG: L1=[1,2,3]
del(L1) L1.clear()
print(L1) o/p ERROR print(L1)
o/p [] empty list
3. Can delete specific elements by 3. Used to remove all elements from
specifying [st_ind:stop_ind:step_val] list.
EG: del L1[0:1:2]
11. count() function
• Returns the number of times the occurrences of specific
value/element in the list. Returns 0 (zero) if doesn’t exists. Returns
the integer value. If argument is string then it is case sensitive.
• EG:
12. reverse() function
• Reverses the items of the list. It is done in place ie in same memory id. Takes
no argument, returns nothing or no list.
• Syntax: <List_Object>.reverse()
EG1: EG2:
13. sort() function
• This function sorts the items of the list in increasing/ ascending order by-
default. Can be sorted in descending order also. Does not create new list,
sorting is done in same memory id.
• Syntax: <List_obj>.sort()
OR
<List_obj>.sort(reverse=False/True)
EG1: default ascending order EG2: sorting in descending order.
• Sorting alphabets

• Sorting lexicographically i.e. dictionary order


14. sorted() function
• This function creates new sorted list. Takes list as an argument and another
optional argument. Will not modify the original list.
• Syntax: <new_List_obj>=sorted(<iterable_sequence>,[reverse=True/False])
(NOTE: iterable_sequence can be list/tuple/string)
• EG:

Descending order
• EG2: sorting tuple EG:4 sorting str

• EG3: sorting string


Difference between sort() and sorted() function
• NOTE: (if you want to sort a list but still want to keep the original
unsorted, then use sorted() function.
15. min(), max(), sum()
• Syntax: min(<list_ob>) will return min number from the list.
• Syntax: max(<list_ob>) will return max number from the list.
• Syntax: sum(<list_ob>) will return sum of numbers from the list.
• EGS:
#WAP to create a list of 1-10 nos and print its sum (without using built-
in sum())
L=list(range(1,11))
print(L)
s=0
for a in L:
s+=a
print(s)
Study the following errors
Study the following code
Working with float values

min() & max() works on ascii values so


o/p is produced. sum() gives an error
as cannot add string data.
• ACII value of ‘A’ is 65 and ‘a’ is 97
• PROGRAMS FROM tb

You might also like