











Lists in python


Introduction to lists
Lists are used to store data in a single variable. Lists in python is same as arrays , the only difference is arrays store only homogeneous type of elements (say all elements must only be integers , float , string) but in lists it stores heterogeneous type of elements. Lists are mutable and indexed where index starts from zero.
Example lists: Lst1=[“a”,”b”,”c”,”d”]
Lst2=[1,2,3,4,5,6]
Lst3=[True,”learn python” ,”with”,”PrepInsta”,440,403]
Keyword used for lists is “list”
Properties of lists
- Lists are indexed
- Lists are mutable
- Lists allow duplicates
- Lists can store heterogeneous datatypes
- Lists can be used as nested format
Declaration of lists in python
An empty list can be declared as two types
- using keyword list()
- using square braces [ ]
List L1 is : []
List L2 is : []
List functions
some of the important functions in python are
- len
- append
- insert
- count
- index
- sort
- reverse
- pop
Len:
len function is used to find the length of the list. It returns integer.
Syntax: len(Lst)
append:
append means adding . append function is used to add elements to the list. Generally it adds elements to the end of the list.
Syntax: Lst.append(element)
insert:
insert function is also used for same purpose as append. But it adds element at the desired place. It takes two arguments , element and index where to be inserted.
Syntax: Lst.insert(index,element)
count:
count function returns the count of particular element that is passed as arguments.
Syntax: Lst.count(element)
index:
index function returns the index of the first occurred particular element from the list.
Syntax: Lst.index(element)
sort:
sort function sorts the list in ascending order
Syntax: Lst.sort(reverse=True/False,key=func)
here reverse and key is optional . If reverse is True then it sort in descending order.
key is parameter on which sorting criteria depends.
reverse:
reverse function will reverse the order of the list.
Syntax: Lst.reverse()
pop:
pop will delete the elements from the list and stores it in a variable. It works on index
Syntax: x=Lst.pop(index_of_element)
Lets check a program using all the above functions
Give inputs to the list :
apple
cat
dog
eye
apple
List after inserting : ['apple', 'bat', 'cat', 'dog', 'eye', 'apple']
Length of the list : 6
count of apple in the list : 2
List after sorting : ['apple', 'apple', 'bat', 'cat', 'dog', 'eye']
List after reversing : ['eye', 'dog', 'cat', 'bat', 'apple', 'apple']
Popped element apple
Final list : ['eye', 'dog', 'cat', 'bat', 'apple']
Login/Signup to comment