Examples of Using Python Data Structures, Part 1: List
Some useful examples of using Python List
Python has four kinds of in-built data structures i.e. List, Dictionary, Set & Tuple. In this article, we will get to explore python lists.
Let's see some common but useful examples using python lists. All these examples are written in Python 3.
List
List indexing
Python list indexing is Zero-based indexing. In which 1st element is indexed as 0, the second element is indexed as 1 as so on…
>>> a_list=['first','second','third','fourth']
>>> print(a_list[0])
first
>>> print(a_list[1])
second
Python also supports Negative-indexing. -1
gives you the last element of the list, -2
gives you the second element from last.
>>> print(a_list[-1])
fourth
>>> print(a_list[-2])
third
List slicing
Python list can be sliced by mentioning index.
list_name[<start_index>:<end_index>:<interval>]
where the list will be sliced from start_index
until end_index
(not inclusive) jumping interval
steps. Any of the three (start_index
,end_index
,interval
) can be blank. If start_index
is missing it will be set to starting index of the list. Similarly if end_index
is missing it will be set to the last index of the list. Let’s see some examples.
>>> a_list[1:3]
['second', 'third']
>>> a_list[-4:-1]
['first', 'second', 'third']
>>> a_list[::2] #every second element from start
['first', 'third']
>>> a_list[1::2] #every second element starting from second
['second', 'fourth']
>>> a_list[::-1] #you can also reverse the list
['fourth', 'third', 'second', 'first']
You can create empty lists using one of the following two ways.
>>> blank_list=[]
>>> type(blank_list)
<class 'list'>
>>> blank_list=list()
>>> type(blank_list)
<class 'list'>
List comprehension
We can use list comprehension to generate a list from another list. It is a shorter way. In the next snippet, we use a loop to generate a list that contains the first character of the a_list
. It also allows python to decide what is the best way ( sequentially or parallelly ) to implement.
>>> ac_list=[]
>>> for item in a_list:
... ac_list.append(item[0])
...
>>> print(ac_list)
['f', 's', 't', 'f']
But if we use list comprehension, then the code will look like this
>>> ac_list=[item[0] for item in a_list]
>>> print(ac_list)
['f', 's', 't', 'f']
List operations
We can perform multiple operations on a list. The most common of them are append, extend, remove, pop, etc. We will see them in action in the following code snippets.
We can append one item at the end of the list using the append method.
>>> a_list.append('fifth')
>>> print(a_list)
['first', 'second', 'third', 'fourth', 'fifth']
We can append multiple elements of one list in another list
>>> a_list.extend([‘sixth’,’seventh’])
>>> print(a_list)
[‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’, ‘sixth’, ‘seventh’]
Note: that if we try to append a list using the append method, the whole list is considered as an item and inserted in the list.
>>> a_list.append([‘sixth’,’seventh’])
>>> print(a_list)
[‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’, ‘sixth’, ‘seventh’, [‘sixth’, ‘seventh’]]
We can remove items from the list using the pop method. Without any argument, it will remove the last element and return the element. We can also remove an item by passing the item index as the argument of the pop method
>>> a_list.pop()
[‘sixth’, ‘seventh’]
>>> print(a_list)
[‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’, ‘sixth’, ‘seventh’]
>>> a_list.pop(3)
‘fourth’
>>> print(a_list)
[‘first’, ‘second’, ‘third’, ‘fifth’, ‘sixth’, ‘seventh’]
An element can be also be inserted in an array by mentioning the index using the insert method
>>> a_list.insert(3,’first’)
>>> print(a_list)
[‘first’, ‘second’, ‘third’, ‘first’, ‘fifth’, ‘sixth’, ‘seventh’]
We can get the number of occurrence of an item in the list
>>> print(a_list.count(‘first’))
2
We can remove the element also using the remove method. In case of multiple occurrences, it will delete the item it first encounters.
>>> a_list.remove(‘first’)
>>> print(a_list)
[‘second’, ‘third’, ‘first’, ‘fifth’, ‘sixth’, ‘seventh’]
To find the existence and position of an item in a list we can use the index method of the list. If an item exists, it returns the index of the item, else it throws ValueError
.
>>> a_list.index('fifth')
3
>>> a_list.index('fourth')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'fourth' is not in list
We can also invoke sort and reverse of the list.
>>> a_list.sort()
>>> print(a_list)
['fifth', 'first', 'second', 'seventh', 'sixth', 'third']
>>> a_list.reverse()
>>> print(a_list)
['third', 'sixth', 'seventh', 'second', 'first', 'fifth']
Now if we want to copy a list to another list. We can simply do that using assignment operator ( =
). But it will cause some issues which we will see in the next example.
>>> b_list=a_list
>>> print(b_list)
['third', 'sixth', 'seventh', 'second', 'first', 'fifth']
>>> b_list.append('seventh') # let's make some changes to the new list
>>> print(b_list)
['third', 'sixth', 'seventh', 'second', 'first', 'fifth', 'seventh']
>>> print(a_list) # The changes happened in the original list as well
['third', 'sixth', 'seventh', 'second', 'first', 'fifth', 'seventh']
We can get around that using the copy method.
>>> b_list=a_list.copy()
>>> print(b_list)
['third', 'sixth', 'seventh', 'second', 'first', 'fifth', 'seventh']
>>> b_list.append('tenth') # let's make some changes to the new list
>>> print(b_list)
['third', 'sixth', 'seventh', 'second', 'first', 'fifth', 'seventh', 'tenth']
>>> print(a_list)
['third', 'sixth', 'seventh', 'second', 'first', 'fifth', 'seventh']
The assignment operator creates a shallow copy where the second list points to the original list. Whereas the copy method creates a whole list containing the elements of the original list.
We can clear the list by using the clear method.
>>> a_list.clear()
>>> print(a_list)
[]
Other operations on List
Fetching the length of the list.
>>> n_list=[1,5,3,4,2]
>>> print(len(n_list))
5
Fetching the maximum and minimum of the list.
>>> print(min(n_list))
1
>>> print(max(n_list))
5
We can also sort the list. It doesn’t affect the original list.
>>> print(sorted(n_list))
[1, 2, 3, 4, 5]
>>> print(n_list)
[1, 5, 3, 4, 2]
That’s some basic example using the list and its methods.
Hope you like it. Stay tuned for more.