Python Lists
A list is a data structure in Python that is a mutable (i.e. modifiable), ordered sequence of elements. Each element of a list is called an item. It allows duplicate items. Python does not have built-in support for arrays, but lists can be used alternatively. Lists are defined by having items between square brackets [ ].
As an ordered sequence of elements, each item in a list can be called separately, through indexing. Lists are a compound data type made up of smaller parts, and are very flexible because they can have values added, removed, and changed. When we need to store a lot of values or iterate over values, and we want to readily modify those values, we will likely want to work with list data types.
Several operations may be performed on a Python list:~
1) Creation of a list:
To create a list in Python we have to put different comma-separated values between square brackets. It can have any number of items and they may be of different types (integer, float, string etc.). A nested list list can be created that even have another list as an item. It is also possible to use the list() constructor with double round-brackets to make a list. See the code below:
# list01.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
print(megacity_list)
mixed_list = [10, "motherland", 15.3] # list with mixed data types
print(mixed_list)
nested_list = ["London", [0, 2, 4, 6, 8], ['X']] # nested list
print(nested_list)
country_list = list(("India", "China", "Russia", "America", "England")) # list() constructor
print(country_list)
Output:
['Delhi', 'Mumbai', 'Kolkata', 'Bengaluru', 'Chennai']
[10, 'motherland', 15.3]
['London', [0, 2, 4, 6, 8], ['X']]
['India', 'China', 'Russia', 'America', 'England']
2) Accessing elements of a list:
To access the list items we have to refer to a specific index or a range of indices (called slicing) separated by a colon [x : y]. Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. See the code below:
# list02.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
print(megacity_list[1])
print(megacity_list[2:5]) # 2nd to 4th position
print(megacity_list[1:]) # 1st to last position
print(megacity_list[-2]) # negative indexing
print(megacity_list[-4:-2]) # negative indexing with range
Output:
Mumbai
['Kolkata', 'Bengaluru', 'Chennai']
['Mumbai', 'Kolkata', 'Bengaluru', 'Chennai']
Bengaluru
['Mumbai', 'Kolkata']
3) Changing element of a list:
It is easier to change the element of a list:
# list03.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
print("Before: ")
print(megacity_list)
megacity_list[3] = "Bangalore" # element changed
print("After: ")
print(megacity_list)
Output:
Before:
['Delhi', 'Mumbai', 'Kolkata', 'Bengaluru', 'Chennai']
After:
['Delhi', 'Mumbai', 'Kolkata', 'Bangalore', 'Chennai']
4) Looping through a list:
It is easier to loop through the elements of a list:
# list04.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
for item in megacity_list:
print(item)
Output:
Delhi
Mumbai
Kolkata
Bengaluru
Chennai
5) Length of a list:
It is easier to count the number of elements in a list using the len() method:
# list05.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
print(len(megacity_list))
Output:
5
6) To check if an element exists in a list:
To check if an element exists in a list we use the ‘in’ keyword:
# list06.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
item = "Chennai"
if item in megacity_list:
print("Yes, 'Chennai' is in the megacity list")
Output:
Yes, 'Chennai' is in the megacity list
7) Add an item to the end of a list:
We can use the append() method to add an item to the end of list or add several items using the extend() method. We can also use + operator to combine two lists. This is also called concatenation. The * operator repeats a list for the given number of times. See the code below:
# list07.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
megacity_list.append("Ahmadabad")
print(megacity_list)
odd_list = [1, 3]
odd_list.append(5)
print(odd_list)
odd_list.extend([7, 9])
print(odd_list)
even_list = [0, 2, 4]
print(even_list + [6, 8])
print(["repeat"] * 3)
Output:
['Delhi', 'Mumbai', 'Kolkata', 'Bengaluru', 'Chennai', 'Ahmadabad']
[1, 3, 5]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8]
['repeat', 'repeat', 'repeat']
8) Insert an item to a list:
We use the insert() method to insert an item to the specific position of a list:
# list08.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
megacity_list.insert(4, "Hyderabad")
print(megacity_list)
Output:
['Delhi', 'Mumbai', 'Kolkata', 'Bengaluru', 'Hyderabad', 'Chennai']
9) Remove item from a list:
There are various methods to remove items from a list.
We can use the remove() method to delete a specific item from the list:
# list09.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
megacity_list.remove("Bengaluru")
print(megacity_list)
Output:
['Delhi', 'Mumbai', 'Kolkata', 'Chennai']
The pop() method removes item from the given index (or the last item if index is not given):
# list10.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
megacity_list.pop(2)
print(megacity_list)
megacity_list.pop()
print(megacity_list)
Output:
['Delhi', 'Mumbai', 'Bengaluru', 'Chennai']
['Delhi', 'Mumbai', 'Bengaluru']
The ‘del’ keyword deletes item from the specified index or can delete the list completely:
# list11.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
del megacity_list[1]
print(megacity_list)
del megacity_list # don't try to print the list as it will show error
Output:
['Delhi', 'Kolkata', 'Bengaluru', 'Chennai']
The clear() method makes the list empty:
# list12.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
megacity_list.clear() # creates empty list
print(megacity_list)
Output:
[]
10) Reversing a list:
A list can be reversed using the reverse() method:
# list13.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
megacity_list.reverse()
print(megacity_list)
Output:
['Chennai', 'Bengaluru', 'Kolkata', 'Mumbai', 'Delhi']
11) Sorting a list:
We sort the elements in a list using the sort() method:
# list14.py
megacity_list = ["Mumbai", "Kolkata", "Delhi", "Bengaluru", "Chennai"]
megacity_list.sort()
print(megacity_list)
Output:
['Bengaluru', 'Chennai', 'Delhi', 'Kolkata', 'Mumbai']
12) Copying a list:
It is easier to copy the contents of a list to another using the copy() method:
# list15.py
megacity_list = ["Delhi", "Mumbai", "Kolkata", "Bengaluru", "Chennai"]
copy_list = megacity_list.copy()
print(copy_list)
Output:
['Delhi', 'Mumbai', 'Kolkata', 'Bengaluru', 'Chennai']