Lists in Python
- 1 Lists in Python
- 2 Python List Operations
- 3 List Methods in Python
- 4 List Manipulation
- 5 Conclusion
In this tutorial, I am going to discuss about List Datatype in Python, different operations which can be performed on lists and built-in functions available in python for lists.
Lists in Python
In python, we do not have arrays like we have in C++ or Java. So, instead of arrays python has lists which are more useful and versatile than normal arrays in C++ or Java.
List is an ordered collection of python objects. It is a versatile and flexible data collection in python and hence it is also a highly used data type in python.
Creating a List
A list is a collection of arbitrary objects of different data types in a particular order, which are separated by commas enclosed within square brackets ( [ ] ).
A list in python in similar to an array in C, the only difference is list can contain items of different data types.
Following is an example of list which contains objects of multiple datatypes.
list1 = [1, a, [2, 3], (b,c) ]
Following table shows different type of list declarations in python.
|L1 = [ ]||Empty list|
|L2 = [0, 1, 2, 3] or ['a','b','c','d']||Simple declaration of a list with 4 values|
|L3 = [2, 'abc', [3, 'def', 'ghi']]||Nested sublists|
|L4 = list('Welcome to Learn Python')||List of an iterable item|
|L5 = list(range(-2,9))||List of successive integers from -2 to 8|
The first 2 declarations are pretty straight forward, first one is an empty list and second one is the simple list declaration with all elements of same datatypes.
The third expression is a nested list which means there is a list inside a list.
The fourth and fifth declaration shows how we can create a list using iterable object in python.
Let's see some examples on creating a list.
list1 = [1, 'a' , [2, 'b', 3, 'cde']] print("Nested List : ", list1) print("Accessing an element from list inside a list : list1 - ", list1 ) list2 = list("Learning is Fun") print("List from an iterable item : ",list2) list3 = list(range(-2,5)) print("List from range() function : ",list3)
Nested List : [1, 'a', [2, 'b', 3, 'cde']] Accessing an element from list inside a list : list1 - cde List from an iterable item : ['L', 'e', 'a', 'r', 'n', 'i', 'n', 'g', ' ', 'i', 's', ' ', 'F', 'u', 'n'] List from range() function : [-2, -1, 0, 1, 2, 3, 4]
Accessing Elements in a List
Lists are ordered collections, so items of a list are indexed starting from 0. The indexing operator [ ] is used to access a single item present in the list at the index given as input.
To access a sub-part of the list slicing operator [ : ] can be used which takes two integers and gives the list within that indices.
Let's see some examples about accessing the elements of list.
list1 = [ 'abc', 123, 10.34, 'name', 23, '6th', '7th'] list2 = [ 134, 'welcome'] print('list1 - ',list1) #printing complete list print('list1 - ',list1) #printing first element of the list print('list1[1:4] - ',list1[1:4]) #printing elements from 1 to 4 index in the list print('list1[4:] - ',list1[4:]) #printing elements with index starting from 4 print('list1[-2:] - ', list1[-2:]) # printing all elements from second last element of the list. print('list2 - ',list2) #printing element of a nested iterable in a list
list1 - ['abc', 123, 10.34, 'name', 23, '6th', '7th'] list1 - abc list1[1:4] - [123, 10.34, 'name'] list1[4:] - [23, '6th', '7th'] list1[-2:] - ['6th', '7th'] list2 - o
Traversing through a List
We have discussed about for and while loops in python. These can be used to traverse or iterate through a list. Traversing or iterating means accessing and processing each element of the sequence which can be done by using loops in python.
For example, the below shown example prints each element of a list.
list3 = ["P","y","t","h","o","n","C","o","d","e"] for elem in list3: print(elem)
P y t h o n C o d e
Thus by using loops, we can access and process each and every element of a list.
Python List Operations
Lists are similar to Strings in many way, but there an important difference between a list and a string in python which is a string in python is immutable whereas a list is a mutable in python object.
Lists also have same operations as strings like concatenation, repetition and other.
Let us discuss about different operations on lists in python one by one.
Concatenating two lists means joining two or more than two lists to create a new list. It is performed using + operator in python.
The + operator takes two lists as operands and joins them together as output.
Let's see some examples :
list1 = [1,3,6] list2 = [2,4,5] new_list = list1 + list2 print("list1 : ", list1," list2 : ", list2) print("list1 + list2 = ",new_list)
list1 : [1, 3, 6] list2 : [2, 4, 5] list1 + list2 = [1, 3, 6, 2, 4, 5]
But we have to make sure that when + is used with lists both the operands should be of list type, otherwise an error will be shown.
For example :
lst = list1 + 8
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) < ipython-input-16-1f071cdf75b2 > in < module > ----> 1 lst = list1 + 8 TypeError: can only concatenate list (not "int") to list
Repeating a List
Just like with strings, the * operator is used to repeat a list multiple number of times and create a new list.
It takes a list and a number as operands, the number is the number of times the list should be repeated. Just like + operator, the * operator also gives TypeError if we do not use an integer and a list as operands.
Let's see some examples below :
print("list1 : ",list1) print("list1 * 3 = ",list1 * 3)
list1 : [1, 3, 6] list1 * 3 = [1, 3, 6, 1, 3, 6, 1, 3, 6]
We have discussed about membership operators in and not in while discussing about different operators in python.
These operators can be used with list operands to check if an element is present within a list.
Let's see the use of these operators with lists in python.
print(3 in [1,2,3])
print('a' not in ['a','b','c'])
We know that we use slicing operator [ : ] in strings to get sub-strings, similarly we can the slicing operator to get sub-part of a list.
We can use the indices of list elements to create a list slices. Following is the syntax :
part = Lst[ start : stop ].
In the syntax, start and stop refers to indices of the list which wish to include in the sub-part. Note that value present at the stop index is excluded from the sub-part.
We can use positive and negative integers as indices, here negative indices means that start from last element of a list towards first element of the same list.
If the index given is not present in the list then we will get Index Error.
Let's see some examples :
list5 = [10,25,37,42,24,67,59,89,47,26] print("list5[2:6] - ",list5[2:6]) print("list5[-4:] - ",list5[-4:]) print("list5[:6] - ",list5[:6]) print("list5 - ", list5)
list5[2:6] - [37, 42, 24, 67] list5[-4:] - [59, 89, 47, 26] list5[:6] - [10, 25, 37, 42, 24, 67] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) < ipython-input-2-709eccff3c97 > in < module > 3 print("list5[-4:] - ",list5[-4:]) 4 print("list5[:6] - ",list5[:6]) ----> 5 print("list5 - ", list5) IndexError: list index out of range
In the last example, IndexError is thrown because the list contains only 10 elements which means the indices range from 0 to 9 hence 15th index is not present.
List also supports another syntax of slice operator as shown below :
part2 = Lst[ start : stop: step ]
In the above syntax start and stop have same meaning but a new step value is given to the slice operator.
The step value means to skip that number of values while creating the sub-list. The default value for step is 1 but if we wish to increase the difference between the indices of the sub-list then we can provide the value as step.
Let's understand this with example :
print("list5 = ", list5) print("list5[0:10:2] = ",list5[0:10:2])
list5 = [10, 25, 37, 42, 24, 67, 59, 89, 47, 26] list5[0:10:2] = [10, 37, 24, 59, 47]
So, when we put the value of step as 2 we get every 2nd element of the list from start to stop index.
Copy of List
When we want to make a copy of the list in python, we generally do it using assignment operation ( = ). Like shown below :
Lst = [1,2,3] New = Lst print(Lst) print(New)
[1, 2, 3] [1, 2, 3]
Now suppose we would change an element of the first list, let's see then what will be the values in Lst and New lists.
Lst = 5 print("Lst = ",Lst) print("New = ",New)
Lst = [1, 2, 5] New = [1, 2, 5]
In the above example,new list gets automatically updated if we update the Lst list.
We have discussed that variables in python are labels which get assigned to a value.
Here we can see the example of that, as Lst and New are two different labels but are assigned to the same list. This explains why New list also gets updated if we change the Lst list.
So, there are other ways through which we can make copy of a list and the copy will not change if we update the original list. That is it will be an independent copy also known as true copy of the list. Let's see how.
1. Using list( ) method
list() method is generally used to typecast or convert an iterable object like string or tuple into a list. But it can also be used to make a copy of a list which will be independent from the original list.
Let's see an example:
Lst1 = [1,2,3] Lst2 = list(Lst1) print("Lst1 = ",Lst1) print("Lst2 = ",Lst2) Lst1 = 4 print("After updating Lst1") print("Lst1 = ",Lst1) print("Lst2 = ",Lst2)
Lst1 = [1, 2, 3] Lst2 = [1, 2, 3] After updating Lst1 Lst1 = [1, 2, 4] Lst2 = [1, 2, 3]
2. Using copy( ) method
Python also provides a built-in
copy() method to make true copy of a list. the syntax to use
copy() method is :
New = L.copy( )
Here, New is the true copy and L is the list to be copied.
Let's see an example :
Lst = ['a','b','c'] New = Lst.copy() print("Lst = ",Lst) print("New = ",New) Lst = 'd' print("After updating Lst") print("Lst = ",Lst) print("New = ",New)
Lst = ['a', 'b', 'c'] New = ['a', 'b', 'c'] After updating Lst Lst = ['a', 'b', 'd'] New = ['a', 'b', 'c']
List Methods in Python
Python also provides methods for list manipulation in addition to the operations we just saw. These built-in methods help us process and manipulate lists more easily.
Following is a list of methods provided in python for list manipulation along with small description about each of them.
||Add an element to the end of list|
||Add all elements of a list to another list|
||Insert an item at the defined index|
||Removes an item from the list|
||Removes and returns an element at the given index.|
||Removes all items from the list|
||Returns the index of the first matched item|
||Returns the count of the number of items passed as an argument|
||Sort items in a list in ascending order|
||Reverse the order of items in the list|
||Returns a true copy of the list|
Some examples of Python list methods :
list_ex = [6,32,7,9,44,3,63,21,34,7,2] print("index() : ",list_ex.index(6)) print("count() : ",list_ex.count(7)) list_ex.sort() print("sort() : ",list_ex) list_ex.reverse() print("reverse() : ",list_ex)
index() : 0 count() : 2 sort() : [2, 3, 6, 7, 7, 9, 21, 32, 34, 44, 63] reverse() : [63, 44, 34, 32, 21, 9, 7, 7, 6, 3, 2]
We will learn about these functions as we learn in further articles with more examples.
So till now, we have seen creating and accessing lists, operations on lists and built-in methods for list in python.
Before we go ahead, you should note that lists in python are mutable objects which means that we can modify/update elements of a list.
Now, we will discuss other list manipulations which are append elements to a list, update/modify a list and delete operation on a list.
So, let's learn about these one by one.
Appending Elements to a List
1. Appending a single element
If we wish to append a single element to a list, then python provides
append() method for this purpose. The
append() method is used as follows :
Consider an example :
list_a = [1,2,3,4] print("list_a = ",list_a) list_a.append(5) print("After appending : list_a = ",list_a)
list_a = [1, 2, 3, 4] After appending : list_a = [1, 2, 3, 4, 5]
2. Appending a list of elements to a list
append() method is used to appends an element to a list but if we wish to append a list of elements to a list then we use
extend() method. The
extend() method is used as follows :
L.extend(list of elements)
Look at the following example to understand better :
list_b = ['a','b','c','d'] print("list_b = ",list_b) list_b.extend([1,2,3]) print("After extending : list_b = ",list_b)
list_b = ['a', 'b', 'c', 'd'] After extending : list_b = ['a', 'b', 'c', 'd', 1, 2, 3]
Deleting Elements from a list
We can delete an element from a list using its position/index or by using its value with help of built-in methods for lists. We can also delete multiple elements from a list using the slicing operation along with del keyword.
Let's see how this works.
1. Deleting an Element using it position/index
Python gives a built-in method
pop() using which we can delete an element from a list. It takes position/index of the element to be deleted as argument, it returns the element at the index given and updates the list.
Let's see an example below :
lst1 = [1,2,3,4,5] print("original list : ",lst1) print("output of pop() method : ",lst1.pop(3)) print("list after pop() : ",lst1)
original list : [1, 2, 3, 4, 5] output of pop() method : 4 list after pop() : [1, 2, 3, 5]
2. Deleting an Element using its value
If we want to delete an element from a list but using its value, then python gives us a built-in method
remove() which takes an element value to be deleted as argument.
It removes the first occurrence of the value of argument and updates the list.
If we give a value which is not present in the list as an argument to
remove(), then ValueError will be shown which means that value is not present.
Let's understand this better using examples :
lst2 = [1,2,3,4,5,1,1] print("original list : ",lst2) lst2.remove(1) print("list after remove()", lst2) lst2.remove(8) # Throws value error
original list : [1, 2, 3, 4, 5, 1, 1] list after remove() [2, 3, 4, 5, 1, 1] --------------------------------------------------------------------------- ValueError Traceback (most recent call last) < ipython-input-82-755244e48115 > in < module > 3 lst2.remove(1) 4 print("list after remove()", lst2) ----> 5 lst2.remove(8) ValueError: list.remove(x): x not in list
3. Deleting a sub-list from a List
the del keyword from python can be used to delete an individual element or a sublist from a list. Syntax for using del keyword is given as :
del list [ index ]
del list [ start : stop ]
Consider the following examples :
lst3 = [1,2,3,4,5,6,7,8,9,10,11,12] print("original list : ",lst3) del lst3 print("After del lst3 : ",lst3) del lst3[4:8] print("After del lst3[4:8] : ",lst3)
original list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] After del lst3 : [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12] After del lst3[4:8] : [1, 2, 3, 4, 10, 11, 12]
If you want to delete a complete list then you can use del listname. After this, no object with the listname will be existing.
You can also create a list using list comprehension in python.
To create a list using this way, we have to type an expression followed by a for loop statement all inside a square bracket.
Following is an example showing use of list comprehension.
squar = [i*i for i in range(1,11)] print(squar)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
We can also add an if statement to filter out the output of for statement.
Following is an example of list comprehension with if statement.
squar2 = [i*i for i in range(1,21) if i%3==0] print(squar2)
[9, 36, 81, 144, 225, 324]
In this tutorial, we have discussed about list datatype in python. Creating and accessing a list, operations on lists in python, built-in methods for lists, list manipulations and list comprehensions in python.
If you have any questions please comment below also share your views and suggestions in the comment box.