From printing something, to decision making, to iterating using loops, we have learned many concepts till now. This and the next few chapters are going to be about storing data. So, let’s start with a list which is used to store a list
of data.
We often need a list in our programs. Imagine you are writing a program to store the marks of every student in a class of 50 students. Taking 50 different variables is not a good option. Instead of that, we can store all those 50 values (marks) as a list in a single variable. Cool, right?
Creating a List in Python
[]
is a list.
[1,2,3]
is a list having elements 1, 2 and 3 in it.
a = [1, 2, 3, 4, 5]
→ Here, a
is a list having elements 1, 2, 3, 4 and 5 in it.
The items/elements in a list are enclosed within brackets [ ]
and separated by commas.
a=[]
a
is an empty list having no item.
mylist = [2, "Hello", True, 100, 2]
print(mylist)
mylist
is a list having five items of different data types.
print(type([]))
As you can see, type([])
is showing the type as list. This means that [ ] is a list as already mentioned.
Python Accessing Elements from List
A particular element from a list can be accessed using its index.
Every element in a list has a unique index based on its position. Indices start from 0. Therefore, the first element of a list has index 0, the second element has index 1, and so on.
Take the following list.
mylist = [“a”, “b”, “c”, “d”, “e”]
In this list, the index of “a” is 0, “b” is 1, “c” is 2, “d” is 3 and “e” is 4. Thus, the index started from 0 and went up to 4.
element | "a" | "b" | "c" | "d" | "e" |
index | 0 | 1 | 2 | 3 | 4 |
A particular element from a list can be accessed using its index.
To access any element of a list, we write name_of_list[index]
.
Therefore, the 2nd element of the list mylist
can be accessed by writing mylist[1]
(because the index of the 2nd element is 1).
mylist = [4,9,6,2]
print(mylist[0])
print(mylist[1])
print(mylist[2])
print(mylist[3])
So, we can use a list to store a collection of data, for example, marks of 50 students, and to access each element, we can simply use list_name[index].. This is quite convenient instead of storing marks in 50 different variables.
Negative Index in Python List
We can also access an element of a list by using the negative value of the index. Negative indices behave differently.
The last element of a list has index -1, second last element has index -2, and so on.
element | "a" | "b" | "c" | "d" | "e" |
Negative index | -5 | -4 | -3 | -2 | -1 |
The following example will make you understand better.
mylist = [4,9,6,2]
# accessing using negative indices
print(mylist[-1])
print(mylist[-2])
print(mylist[-3])
print(mylist[-4])
Here, mylist[-1] returns the last element 2 of the list mylist, mylist[-2] returns the second last element 6, and so on.
Python Slicing
Suppose we have a list of the marks of 50 students. Now, if from this list, we want the marks of only the first 10 students, then we can do so by slicing the list to get only the first 10 elements.
We can slice a list using the slicing operator.
To access elements from the ith index to the jth index of a list, we write name_of_list[i:j+1]
.
mylist = [1,2,3,4,5]
print(mylist[1:4])
mylist[1:4]
returned the elements from the 1st index to the 3rd index i.e., [2, 3, 4].
To access the elements from index 4 till the end of a list, use name_of_list[4:].
To access the elements from the start till index 4 of a list, use name_of_list[:5].
To access all the elements from the start till the end of a list, use name_of_list[:].
mylist = [1, 2, 3, 4, 5, 6]
# from 2nd element till 5th element
print(mylist[1:5])
# from start till 5th element
print(mylist[:5])
# from 5th element till end
print(mylist[4:])
# from start till 3rd last element
print(mylist[:-2])
# from 4th last element till 3rd last element
print(mylist[-4:-2])
# from 3rd element till 3rd last element
print(mylist[2:-2])
# all elements
print(mylist[:])
We can also give a step to the slice to skip some number of elements while slicing.
Look at the following example.
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# from 2nd element till 9th element
print(mylist[1:9])
# from 2nd element till 9th element in step 2
print(mylist[1:9:2])
# from 2nd element till 9th element in step 3
print(mylist[1:9:3])
mylist[1:9]
returned the elements from the 1st index till the 8th index.
mylist[1:9:2]
also returned the elements from the 1st index till the 8th index, but it returned every 2nd element after the element having the start index. Therefore, 3, 5 and 7 got skipped.
mylist[1:9:3]
also returned the elements from the 1st index till the 8th index, but it returned every 3rd element after the element having the start index.
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# from 3rd element till 9th element
print(mylist[2:9])
# from 3rd element till 9th element in step 2
print(mylist[2:9:2])
# from 3rd element till 9th element in step 3
print(mylist[2:9:3])
# from start till 9th element in step 2
print(mylist[:9:2])
# from 3rd element till end in step 3
print(mylist[2::3])
# elements from start till end in step 2
print(mylist[::2])
Giving a negative step will return the elements of a list in the reverse order. A step of -1 returns the reversed list.
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# reversed list
print(mylist[::-1])
# reversed list with step -2
print(mylist[::-2])
Changing Elements of List in Python
Lists are mutable, which means that their elements can be changed.
Changing any element of a list is simple. We know that using list_name[index], we can access any element of a list. We can simply change that element using list_name[index] = some_value. This will change the value of the element at index in the list my_list to some_value.
Changing a Single Element of List in Python
mylist = [1, 2, 3, 4, 5, 6]
mylist[2] = 0 # changing 3rd element, at index 2
print(mylist) # printing changed list
The third element of the list is changed by simply assigning the new value to mylist[2]
.
Changing range of elements in Python List
mylist = [1, 2, 3, 4, 5, 6]
mylist[2:5] = [10, 11, 12] # changing 3rd to 5th elements
print(mylist) # printing changed list
A range of elements from the 2nd index till the 4th index is changed by assigning a list of values to mylist[2:5]
.
Adding Elements to Python List
Adding a Single Element to Python List
To add one element to the end of a list, we can use the append()
function. The append()
function appends the element (adds the element at the last) to a list.
mylist = [1, 2, 3, 4]
mylist.append(5) # 5 is added to the list
print(mylist) # printing changed list
You can see that 5 got appended (added at the last) to the list mylist
.
To add one element at a specific position of a list, we use the insert()
function. The insert()
function takes two arguments - the first argument is the index where we want to insert and the second argument is the element which we want to insert.
mylist = [1, 2, 3, 4]
mylist.insert(2, 5) # adding 5 at index 2 of the list
print(mylist) # printing changed list
In this example, 5 is added at the 2nd index of the list mylist
.
Adding Multiple Elements to Python List
To add multiple elements to the end of a list, we use the extend()
function. The extend()
function takes a list and inserts all of its elements at the last of the list on which it is called.
mylist = [1, 2, 3, 4]
mylist.extend([5, 6, 7]) # 5, 6 and 7 are added to the list
print(mylist) # printing changed list
Here, the extend()
function took a list [5, 6, 7] and added the elements 5, 6 and 7 at the last of the list mylist
.
Instead of using the extend()
function, we can also concat a list using the +
operator. However instead of changing the current list, it will give us a new list. Let’s look at an example.
mylist1 = [1, 2, 3]
mylist2 = [4, 5]
mylist3 = mylist1+mylist2
print(mylist1)
print(mylist3)
Here, you can see that “+” joined two lists and gave us a new list. However, mylist1
and mylist2
are unchanged.
As stated above, we can also change the range of a list and that will be helpful if we want to insert multiple elements at any specific position in a list.
mylist = [1, 2, 3, 4]
mylist[2:2] = [5, 6, 7] # adding 5, 6 and 7 starting from index 2 of the list
print(mylist) # printing changed list
In this example, we assigned the list [5, 6, 7] to mylist[2:2]
. This means that [5, 6, 7] is inserted from the 2nd index onwards of mylist
. Thus, 5, 6 and 7 are inserted to the list at indices 2, 3 and 4 respectively.
Python Deleting Elements from List
Python del
The del
keyword can be used to delete a single element, multiple elements or the entire list.
colors = ["Blue", "Green", "Red", "Orange", "Yellow", "Brown"]
del colors[2] # deleting 3rd element
print(colors)
In the above code, the third element is deleted from the list.
colors = ["Blue", "Green", "Red", "Orange", "Yellow", "Brown"]
del colors[2:4] # deleting from 3rd element to fourth element
print(colors)
In the above code, the elements at the 2nd and 3rd indices are deleted from the list.
colors = ["Blue", "Green", "Red", "Orange", "Yellow", "Brown"]
del colors # deleting the list
print(colors)
In the above code, the entire list colors
is deleted. Thus, we got an error on printing the list after deleting it.
Python remove()
The remove()
function is used to remove a particular element from a list.
colors = ["Blue", "Green", "Red", "Orange", "Yellow", "Brown"]
colors.remove("Green") # removing "Green" from list
print(colors)
colors.remove("Green")
removed "Green" from the list colors
.
If the element passed to the remove()
function is present more than once in the list, then the element with the first occurrence is deleted.
colors = ["Blue", "Green", "Red", "Orange", "Green", "Brown"]
colors.remove("Green") # removing "Green" occurring first from list
print(colors)
"Green" is present at indices 1 and 4. However, only "Green" present at index 1 got deleted.
Python pop()
The pop()
function removes an element from the specified index and returns the removed element.
colors = ["Blue", "Green", "Red", "Orange", "Yellow", "Brown"]
print(colors.pop(3)) # removing the 4th element from list and printing the removed element
print(colors) # printing updated list
colors.pop(3)
removed the element at the 3rd index from the list and returned that element. Therefore, on printing the popped value, Orange got printed.
If we don’t pass any index in the pop()
function, then it removes and returns the last element of the list.
colors = ["Blue", "Green", "Red", "Orange", "Yellow", "Brown"]
print(colors.pop()) # removing the last element from list and printing the removed element
print(colors) # printing updated list
Python clear()
The clear()
function removes all the elements from a list.
colors = ["Blue", "Green", "Red", "Orange", "Yellow", "Brown"]
colors.clear() # removing all element from list
print(colors) # printing updated list
Python List Operations
Python Concatenation (+) Operation
Two or more lists can be concatenated or combined using the +
operator.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c', 'd']
list3 = list1 + list2
print(list3)
list1
and list2
are concatenated to form list3
.
Python Repetition (*) Operation
A list can be repeated a specified number of times using the *
operator.
list1 = [1, 2]
list2 = list1 * 3
print(list2)
list1 is repeated 3 times to form list2.
Python List Membership Test
We can test if an element is present in a list using the membership operators in
and not in
.
mylist = [1, 2, "Blue", "Green"]
print(2 in mylist)
print(4 in mylist)
print("Green" not in mylist)
Python Iteration Through a List
We can iterate through a list using a for loop. We have already seen examples of iteration of lists while studying for loops.
colors = ["Blue", "Green", "Red"]
for color in colors:
print(color)
A variable color
goes to each element in the list colors
and takes its value, and that value is printed on the screen.
We can also iterate through the above list using another way.
colors = ["Blue", "Green", "Red"]
for i in range(len(colors)):
print(colors[i])
len()
function is used to return the number of elements in a list. Therefore range(len(colors))
is equal to range(3). This means that there will be three iterations in the loop. You must have understood the rest of the code.
In the first iteration, the value of i is 0, thus printing colors[0], i.e., “Blue”.
In the second iteration, the value of i is 1, thus printing colors[1], i.e., “Green”.
In the third iteration, the value of i is 2, thus printing colors[2], i.e., “Red”.
Now that we know how to iterate through a list, let’s write a program to create a list having 5 values entered by the user.
mylist = [] # creating an empty list
# appending values entered by user to list
for i in range(5):
print("Enter value of n[", i, "]")
mylist.append(input())
# printing final list
print(mylist)
In this program, we are first creating an empty list mylist
.
We already know that range()
is a sequence of numbers. Therefore, range(5)
is a sequence of five numbers (0 to 4), which means that there will be five iterations in the loop. In each iteration, we are reading the value entered by the user using input()
and then appending that value to the list using the append()
function. Therefore, finally our list has five elements.
Python 2D List (List inside List)
We can also have a list inside another list. In other words, a list can have an element which is a list.
mylist = [1, 2, [3, 4, 5], 6]
print(mylist[0])
print(mylist[1])
print(mylist[2])
print(mylist[3])
Here, the third element of the list mylist
is another list [3, 4, 5].
We can access the elements of the inner lists as shown in the following example.
mylist = [1, 2, [3, 4, 5], 6]
print(mylist[2][0])
print(mylist[2][1])
print(mylist[2][2])
mylist[2]
is [3, 4, 5]. So, the first element of mylist[2]
can be accessed by mylist[2][0]
, the second element by mylist[2][1]
and the third element by mylist[2][2]
.
Different Ways to Create a List in Python
We already know how to create a list.
An empty list is created as follows.
mylist = []
A list having elements is created as follows.
mylist = [1, 2, 3, 4]
Lists can also be created using the list()
function. This function converts a sequence (range, list, string, tuple) or a collection(dictionary, set) into a list.
An empty list can be created using list()
as shown below.
mylist = list()
print(mylist)
Now let’s convert a tuple into a list.
mytuple = (1, 2, 3)
mylist = list(mytuple)
print(mylist)
mytuple
is a tuple, which when passed to the list()
function returned a list mylist
.
mystring = "Codesdope"
mylist = list(mystring)
print(mylist)
In the above example, a string is converted into a list. Note that all the characters of the string became the different elements of the list.
Now let’s write a program to create a list having the first ten natural numbers.
mylist = list(range(1, 11))
print(mylist)
Here we converted a range of numbers from 1 to 10 into a list. Similarly, we can create a list of even numbers or odd numbers from 1 to 100. Try it yourself.
Python Copying List
Let’s look at the different ways we can copy a list.
Simple Assignment
A list can be copied to a variable by simply assigning it to the variable.
list1 = [1, 2, 3, 4]
list2 = list1
print(list2)
Here, the list stored in the variable list1
is assigned to the variable list2
. Thus, both the variables store the same list. As a result, if some change is made in list2
, it will also get reflected in list1
, which is often undesirable.
Let’s see how a change in list2
is getting reflected in list1
.
list1 = [1, 2, 3, 4]
list2 = list1
list2[0] = 10
print("Original list:", list1)
print("New list:", list2)
After assigning list1
to list2
, the first element in list2
is changed. On changing this, the first element in list1
also got changed. This is because both the variables are pointing to the memory location of the same list.
To prevent this, we can use the copy()
function.
Python copy()
copy()
is a function in Python which creates a shallow copy of a list.
list1 = [1, 2, 3, 4]
list1 = [1, 2, 3, 4]
list2 = list1.copy()
list2[0] = 10
print("Original list:", list1)
print("New list:", list2)
In this example, a shallow copy of list1 is created using copy() and that copy is assigned to list2. As a result, modifying list2 didn’t modify list1 because now the variables are pointing to the memory addresses of different lists.
Python Slicing Operator ( : )
A list can also be copied using the slicing operator. This is the fastest way to copy a list.
list1 = [1, 2, 3, 4]
list2 = list1[:]
list2[0] = 10
print("Original list:", list1)
print("New list:", list2)
Python list()
A list can be copied by passing it to the list()
function.
list1 = [1, 2, 3, 4]
list2 = list(list1)
list2[0] = 10
print("Original list:", list1)
print("New list:", list2)
We created a new list having all the elements of list1
using list(list1)
and assigned this newly created list to list2
.
Python extend()
Another way to copy a list is to add it to an empty list using the extend()
function.
list1 = [1, 2, 3, 4]
list2 = []
list2.extend(list1)
list2[0] = 10
print("Original list:", list1)
print("New list:", list2)
We created an empty list list2
and added list1
to it by writing list2.extend(list1)
. So, now list2
consists of all the elements of list1
.
Built-in List Functions in Python
The functions available in Python which can be used with lists are shown below.
Python len()
It returns the number of elements in a list.
mylist = [1, 2, 3, 4, 5, 6]
print(len(mylist))
Python max()
It returns the element from a list that has the maximum value.
mylist = [3, 2, 1, 5, 6, 4]
print(max(mylist))
Python min()
It returns the element from a list that has the minimum value.
mylist = [3, 2, 1, 5, 4]
print(min(mylist))
Python sum()
It returns the sum of all the elements in a list.
mylist = [3, 2, 1, 5, 6, 4]
print(sum(mylist))
Python sorted()
It returns a sorted list of a sequence (list, string, tuple, range) or a collection (dictionary, set).
mylist = [3, 2, 1, 5, 6, 4]
print(sorted(mylist))
Here the elements of the list mylist
got sorted.
In the next example, a tuple mytuple
got converted into a list with its elements sorted.
mytuple = (3, 2, 1)
print(sorted(mytuple))
To sort the elements in descending order, pass another argument reverse=True
to the sorted
function as shown below.
mylist = [3, 2, 1, 5, 6, 4]
print(sorted(mylist, reverse=True))
Python any()
It returns True if any of the elements in a list are True. Otherwise, it returns False.
mylist = [3, 2, 1, True]
print(any(mylist))
any(mylist)
returned True because all the elements of the list mylist
are non-zero or True.
Look at another example where one element of the list is False.
mylist = [3, 2, 1, False]
print(any(mylist))
We have one element of the list False, but still the any()
function returned True. This is because if atleast one element is non-zero or True, then the function returns True.
Now consider the following example.
mylist = ["", 0, False]
print(any(mylist))
The function returned False because the first element is a null string, the second element is 0 and the third element is False.
Python all()
It returns True if all the elements in a list are True. Otherwise, it returns False.
mylist = [3, 2, 1, True]
print(all(mylist))
mylist = [3, 2, 1, False]
print(all(mylist))
In this example, one element is False and so the all()
function returned False.
Other Python List Functions
We have already looked at some of the list functions like append()
, insert()
, extend()
, remove()
, pop()
, clear()
and copy()
. Other useful functions are shown below.
Python index()
It returns the index of the specified element in a list.
languages = ['Python', 'C', 'Java', 'C++']
print(languages.index('Java'))
languages.index(‘Java’)
returned the index of 'Java' in the list languages
.
If the specified element occurs more than once in a list, then the index of its first occurrence is returned as shown below.
languages = ['Python', 'C', 'Java', 'C++', 'Java']
print(languages.index('Java'))
In the above example, 'Java
' is present at the indices 2 and 4 in the list languages
. However, with the index()
function, only the index 2 of its first occurrence got returned.
We can also pass the start index from which we want the search to begin and the end index upto which we want the search to take place.
languages = ['Python', 'C', 'Java', 'C++', 'Java', 'Perl']
print(languages.index('Java', 3)) # 'Java' is searched after index 3
print(languages.index('Java', 1, 3)) # 'Java' is searched between index 1 and index 3
languages.index(‘Java’, 3)
returned the index of 'Java' after index 3 (3 is the start index).
languages.index(‘Java’, 1, 3)
returned the index of 'Java' between indices 1 and 3 (1 is the start index and 3 is the end index).
Python count()
It returns the number of times the specified element occurs in a list.
languages = ['Python', 'C', 'Java', 'C++', 'Java']
print(languages.count('Java'))
Python sort()
It sorts the elements of a list in ascending or descending order.
numbers = [10, 20, 15, 30, 25]
numbers.sort() # sorting the elements
print(numbers) # printing sorted list
numbers.sort()
sorted the elements of the list number
is ascending order.
If nothing is passed to the sort()
function, then the list is sorted in ascending order. In order to sort the list in descending order, we need to pass reverse=True
to the sort()
function.
languages = ['Python', 'C', 'Java', 'C++', 'Perl']
languages.sort(reverse=True) # sorting the elements in descending order
print(languages) # printing sorted list
In this example, the words in the list are sorted in descending order based on the dictionary.
Difference between sort() and sorted()
You might be wondering why we have two separate functions sort()
and sorted()
when both are used to sort lists. It is true that both are used to sort lists, however, there is a small difference.
sort()
changes the original list and doesn’t return anything. Let’s again look at the following example.
numbers = [10, 20, 15, 30, 25]
numbers.sort() # sorting the elements
print(numbers) # printing original list
The original list got updated. numbers.sort()
sorted the elements of the original list numbers
, thus updating it.
On the other hand, sorted()
doesn’t change the original list, but returns the sorted list. Look at the following example to understand this.
numbers = [10, 20, 15, 30, 25]
new_list = sorted(numbers) # sorting the elements of original list and returning the updated list
print("Original list:", numbers) # printing original list
print("Updated list:", new_list) # printing updated list
From the output, we can see that the original list didn’t get updated. sorted(numbers)
sorted the elements of the original list but didn’t update it. Instead, it returned the sorted list which we assigned to new_list
. Therefore, new_list
contains the sorted list.
Python reverse()
It reverses a list.
languages = ['Python', 'C', 'Java', 'C++']
languages.reverse() # reversing the list
print(languages)
You can learn more about lists by reading articles in the Further Reading section at the end of this chapter.