Notes Class 09 Python List Tuple
Notes Class 09 Python List Tuple
Lists
The lists and tuples are Python’s compound data types. They are basically the same
types with one difference. List can be changed or modified i.e. mutable but tuples
cannot be changed or modified i.e. immutable.
A list in Python represents a list of comma separated values of any datatypes between
square brackets.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the
order of the items will not change.
Since lists are indexed, lists can have items with the same value. Lists allow duplicate
values.
Lists
To assign a list to a variable.
list1=[1,2,3,4,5]
list2=[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
list3=[‘DPS’, 12, ‘Bopal’]
List4=[] #empty list
list5=list() #creating an empty list using list function
list6=[3,4,[5,6],7,8] #nested list
print(type(list1)) #will display <class list>
print(list1[1]) #will print 2
print(list2[3]) #will print ‘o’
print(list2[-2]) #will print ‘o’
print(list6[-3])) #will display [5,6]
Lists
list7=list(‘DPS’)
print(list7) #will print [‘D’, ‘P’, ‘S’]
t1=(‘w’, ‘o’, ‘r’, ‘k’) # creates tuple t1
print(list(t1)) #will print [‘w’, ‘o’, ‘r’, ‘k’]
extend(): To append more than one elements or append from another list to the
current list, use the extend() method.
print(list6.extend(11,12)) #will print[3,4,[5,6],7,8,11,12]
Lists
list6=[3,4,[5,6],7,8] (consider this list as reference for the following)
pop(): Removes the element at the specified position Note:
print(list6.pop(1)) # will print [3,[5,6],7,8] In python del is a keyword and
print(list6.pop()) # will print [3,[5,6],7] remove(), pop() are in-built
methods. The purpose of these
remove(): Removes the first item with the specified value three are same but the behavior is
print(list6.remove(7)) # will print [3,[5,6],8] different remove() method delete
values or object from the list using
value and del and pop() deletes
clear(): Removes all the elements from the list values or object from the list using
print(list6.clear()) # will print [] an index.
del: Python del function is used to delete an item from a list at a user-specified index. The
index position of the List del function starts from 0 and ends at n-1
del list6[0] #will print[4,[5,6],7,8]
del list6 # will delete the entire list
print(list 6) # will show error ‘list6 not defined’
Lists
list6=[3,4,[5,6],7,8] (consider this list as reference for the following)
Lists have several built-in Tuple does not have many built-in
5
methods methods.