Python Lists
In this tutorial, we will see various list operations that can be performed on Lists in Python.
Python List Operations
Append list
The append() method is used to appends a new element to the list.
The extend(enumerable) method extends the list by appending elements from another enumerable.
The index() method gets the index of the first occurrence of the input value. If the value is not present in the list a ValueErrorexception is raised. If a second argument is provided, the search begins from that provided index.
This method removes all items from the list.
#Declare the list ls=[3,1,45,6,12,4] #appned the item ls.append(12) print(ls) #output #[3, 1, 45, 6, 12, 4, 12] ls.append(17) #append different type items ls.append(True) ls.append('Hello programmers') print(ls) #Output #[3, 1, 45, 6, 12, 4, 12, 17, True, 'Hello programmers'] #append another list #another list will be added as an item to the list small_list=[14,'python',True] ls.append(small_list) print(ls) #Output #[3, 1, 45, 6, 12, 4, 12, 17, True, 'Hello programmers', [14, 'python', True]]
Extend List
The extend(enumerable) method extends the list by appending elements from another enumerable.
#Declare the list ls1=['a','b','c','d'] ls2=['e','f','g','h'] ls1.extend(ls2); print(ls1) #Output #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Extending non-list enumerable,
#Extend non-list enumerable ls1=[7,1,14,5] ls1.extend(range(10,15)); print(ls1) #Output #[7, 1, 14, 5, 10, 11, 12, 13, 14]
Even, we can concatenate lists with + operator.
#Concatenate list with + operator ls1=[7,1,14,5] ls2=['a','c','s'] ls1=ls1+ls2 print(ls1) #Output #[7, 1, 14, 5, 'a', 'c', 's']
index(value, [beginSearchIndex])
The index() method gets the index of the first occurrence of the input value. If the value is not present in the list a ValueErrorexception is raised. If a second argument is provided, the search begins from that provided index.
ls=[12,True,7,8,1,14,5,8,15] print(ls.index(8)) print(ls.index(8,4)) #Output #3 #7
insert(index, val)
This method inserts value just before the provided index. Therefore, the element occupies this index position after inserting a new element.
ls=[12,True,7,8,1,14,5,8,15] ls.insert(0,'a') #first postion ls.insert(5,19) print(ls) #Output #['a', 12, True, 7, 8, 19, 1, 14, 5, 8, 15]
pop([index])
The pop() method discards and returns the item at the specified index. It removes and returns the last element of the list if no index is provided as input.
ls=[12,True,7,8,1,14,5,8,15] ls.pop(5) ls.pop() print(ls) #Output #[12, True, 7, 8, 1, 5, 8]
remove(value)
The remove(value) method deletes the first appearance of the provided value. If the given value cannot be found, a ValueError is raised.
ls=[12,True,7,8,1,14,5,8,15] ls.remove(15) ls.remove(True) print(ls) #Output #[12, 7, 8, 1, 14, 5, 8] ls.remove(100) # ValueErorr
reverse()
This method is used to reverse the list. (returns None).
count(value)
The count() method is used to count the number of occurrences of the value in the list.
ls=[23,4,31,9,'Hello', 23.56,7,31,17] print(ls.count(31)) #Output #2
sort()
The sort method can be used to sort the list in numerical and lexicographical order. The method returns None.
ls=[23,4,31,9,72, 23,56,7,31,17] ls.sort() print(ls) #Output #[4, 7, 9, 17, 23, 23, 31, 31, 56, 72]
To sort the list in reverse order,
ls=[23,4,31,9,72, 23,56,7,31,17] ls.sort(reverse=True) print(ls) #Output #[72, 56, 31, 31, 23, 23, 17, 9, 7, 4]
Sorting the list by arguments
The argument can be passed to sort() method to sort the list by specific argument.
#Sorting a list of objects #by arguments import datetime class Student(object): def __init__(self,name,roll,birthday): self.name =name self.roll =roll self.birthday =birthday def __repr__(self): return self.name l = [Student("Virat", 15, datetime.date(1995, 4, 12)), Student("Amrit", 21, datetime.date(1994, 1, 28)), Student("Shiva",7, datetime.date(1995, 7, 6))] l.sort(key=lambda x:x.name) print(l) #Output #[Amrit, Shiva, Virat] l.sort(key=lambda x:x.birthday) print(l) #Output #[Amrit, Virat, Shiva] l.sort(key=lambda x:x.roll) print(l) #Output #[Shiva, Virat, Amrit]
Sort by sub dict
for example
l = [{'name':"Virat", 'marks':{'c':75,'java':65,'python':64}, 'birthday': datetime.date(1995, 4, 12)}, {'name':"Amrit", 'marks':{'c':95,'java':74,'python':81}, 'birthday': datetime.date(1994, 1, 28)}, {'name':"Shiva",'marks':{'c':91,'java':45,'python':66}, 'birthday': datetime.date(1995, 7, 6)}] l.sort(key=lambda x:x['marks']['java']) for item in l: print(item['marks']) #Output #{'c': 91, 'java': 45, 'python': 66} #{'c': 75, 'java': 65, 'python': 64} #{'c': 95, 'java': 74, 'python': 81}
another simpler way is by using itemgetter and attrgetter from operator module.
from operator import itemgetter,attrgetter students = [{'name':'Viart','age':24,'roll':45}, {'name':'Amrit','age':23,'roll':11}, {'name':'Shiva','age':22,'roll':29}] by_age =itemgetter('age') by_roll =itemgetter('roll') students.sort(key=by_age) #in-place sorting by age print(students) #output #[{'name': 'Shiva', 'age': 22, 'roll': 29}, #{'name': 'Amrit', 'age': 23, 'roll': 11}, #{'name': 'Viart', 'age': 24, 'roll': 45}] students.sort(key=by_roll) #in-place sorting by roll print(students) #[{'name': 'Amrit', 'age': 23, 'roll': 11}, #{'name': 'Shiva', 'age': 22, 'roll': 29}, #{'name': 'Viart', 'age': 24, 'roll': 45}]
The itemgetter can also be given an index number
from operator import itemgetter,attrgetter #sorting a list of tuples listTuple = [(5,2), (3,8), (5,3)] listTuple.sort(key=itemgetter(1)) print(listTuple) #output #[(5, 2), (5, 3), (3, 8)]
clear()
ls.clear()
Replication
We can generate a larger list containing n times element if we multiply an existing list by an integer n. This can be useful for example for list initialization.
ls=[0]*5 print(ls) #Output #[0, 0, 0, 0, 0]
Deleting the element
The elements from a list can be deleted with the del keyword.
ls = list(range(10)) del ls[::2] # a = [1, 3, 5, 7, 9] del ls[-1] # a = [1, 3, 5, 7] del ls[:] # a = []
Copying the list
The assignment "=" operation assigns a reference of the original list with a new name only. This means that the assigned and assigning both list names are referring to the same list object. As a consequence, the changes made through any of them will be reflected in another. This is often not what you actually want to do.
ls=[8,1,5,4] newls=ls del ls[2] print(newls) #Output #[8, 1, 4]
We have deleted an element from ls, but the effect is the same in the new newls.
We can use a built-in list() method to create a copy of this list, for example
ls=[8,1,5,4] newls=list(ls) del ls[2] print(newls) #Output #[8, 1, 5, 4]
We can also use generic copy module to do the same task,
import copy ls=[8,1,5,4] newls=copy.copy(ls) #inserts references to the objects found in the original. del ls[2] print(newls) #Output #[8, 1, 5, 4]
This might work a little slower than list().
Accessing the Lists
The lists in Python are indexed similar to the arrays in other languages. The elements can be easily accessed by the index positions.
ls=[8,1,5,4,12,6] print(ls[0]) print(ls[2]) print(ls[9]) #IndexError(attempting invalid bound)
We can also use a negative index, the rightmost element has index -1.
ls=[8,1,5,4,12,6] print(ls[-1]) #6 print(ls[-3]) #4 print(ls[-10]) #IndexError(attempting invalid bound)
Lists also support splice notation list[start:end:step]. The slice operation returns a new sliced list containing new elements.
ls=[8,1,5,4,12,6,9] print(ls[:1]) #[8] print(ls[3:]) #[4, 12, 6, 9] print(ls[1:6:2]) #[1, 4, 6] print(ls[::2]) #[8, 5, 12, 9] print(ls[:-1]) #[8, 1, 5, 4, 12, 6] print(ls[-5:-1:2]) #[5, 12] print(ls[-3::2]) #[12, 9]
Checking list emptiness
ls = [] if not ls: print("The list is empty") #Output #The list is empty
Checking if a list contains an item
We can use the in operator to see if the list carries an element or not.
ls = ['RED','BLUE','GREEN','ORANGE'] print('RED' in ls) #True print('PURPLE' in ls) #False
Any and All
All can be used to find if all the elements in the list evaluate to be true. Any can be used to find if any of the elements in the list evaluate to be true. For example,
nums = [1, 1, 0, 1] all(nums) # False chars = ['a', 'b', 'c', 'd'] all(chars) # True nums = [1, 1, 0, 1] any(nums) # True vals = [None, None, None, False] any(vals) # False
zip()
The zip(a, b) returns a list of tuples, where the n-th tuple contains the n-th element from each of the argument sequences or iterables. It can be used to merge two lists.
Xlist = ['X1', 'X2', 'X3'] Ylist = ['Y1', 'Y2', 'Y3'] for a,b in zip(Xlist,Ylist): print(a,b) #OUTPUT #X1 Y1 #X2 Y2 #X3 Y3