List
List is one of the compound data types in Python. Lists can group together elements.
A list is written as a comma-separated , elements (values or items) between square brackets []. Lists might contain elements of different types, but usually the elements all have the same type.
1
# empty list
2
my_list = []
3
​
4
# list of integers
5
my_list = [1, 2, 3, 4]
6
​
7
# list of strings
8
my_list = ['Krakow', 'Warsaw', 'Poznan', 'Wroclaw']
9
​
10
# list with mixed datatypes
11
my_list = ['Krakow', 2, 3.86, True]
Copied!
Python lists are:
  • Lists can be empty
  • Lists can have any elements
  • Lists are ordered
  • List elements can be accessed by index
  • Lists can be nested to any arbitrary depth
  • Lists are mutable, i.e. they can be modified after they are created

Lists can be empty

An empty list can be created by assigning empty square brackets to an identifier.
1
# empty list
2
my_list = []
Copied!

Lists can have any elements

Lists can contain a single datatype or a mixture of datatypes.
1
# list of integers
2
my_list = [1, 2, 3, 4]
3
​
4
# list of floats
5
my_list = [1.2, 2.4, 3.6, 4.8]
6
​
7
# list of strings
8
my_cities = ['Krakow', 'Warsaw', 'Poznan', 'Wroclaw']
9
​
10
# list with mixed datatypes
11
my_list = ['Krakow', 2, 3.86, True]
Copied!

Lists are ordered

The order of elements in a list is important. Two lists are not the same if the elements within a list are same but in a different order.
1
list_01 = [1, 2, 3, 4]
2
list_02 = [4, 3, 2, 1]
Copied!
These two lists have the same elements but in different order
Code
Output
1
list_01 == list_02
Copied!
1
False
Copied!
You can use is keyword too.
Code
Output
1
list_01 is list_02
Copied!
1
False
Copied!

List elements can be accessed by index

You can use the index operator of square brackets[] to access an element in a list. In Python, index starts from 0.
Index number should be an integer, otherwise it raises TypeError. Python will raise an IndexError if the index element is outside of the length of the list minus one.
1
my_cities = ['Krakow', 'Warsaw', 'Poznan', 'Wroclaw']
Copied!

Positive Indexing

The indices for the elements are as follow:
Positive Index
You can access each element by writing the name of the list followed by square brackets [] and index numberof the element.
1
my_cities[0]
2
# OUTPUT:
3
'Krakow'
4
​
5
my_cities[3]
6
# OUTPUT:
7
'Wroclaw'
Copied!

Negative indexing

Python allows negative indexing for elements in a list. Negative index counts from the end of the list. -1 is the index of last element, -2 is the index of second from last element, so on.
Negative Index
You can access elements in a list using negative index.
1
my_cities[-1]
2
# OUTPUT:
3
'Wroclaw'
4
​
5
my_cities[-3]
6
# OUTPUT:
7
'Warsaw'
Copied!

List slicing in Python

Slicing of a list needs two indices: start index and end index separated by a colon :
All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list.
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
Copied!
You create a new list using slice operations. Square brackets [] with colon : will select all elements in the list and assign it to a new list
1
new_list = my_list[:]
Copied!
Let's compare my_list with new_list
== comparison
Output 1
is keyword comparison
Output 2
1
my_list == new_list
Copied!
1
True
Copied!
1
my_list is new_list
Copied!
1
False
Copied!
While comparing new_list with my_list with ==, Python returns True but comparison with Python keyword is returns False. == compares the orders of elements in themy_list and new_listbut Pythonis keyword is referencing memory locations of the my_list and new_list which are different and returns False.

Slicing to select/filter elements

Let's say you want to get the 2nd to 7th elements. Our start index is 1 and end index is 7 (End index returns the index before index 7, so in this case until index 6).
Code
Output
1
# value 2nd to 7th
2
start_index = 1
3
end_index = 7
4
my_list[start_index:end_index]
5
my_list[1:7] # you can write it this way too.
Copied!
1
[3, 4, 5, 5, 7, 8]
Copied!
Lists usually start counting from left to right. Empty start index location means select/filter elements from the start.
Code
Output
1
# value beginning to 6th
2
my_list[:6]
Copied!
1
[2, 3, 4, 5, 5, 7]
Copied!
Empty end index location means select/filter the elements from start index to the last element in the list.
Code
Output
1
# value 6th to the end
2
my_list[5:]
Copied!
1
[7, 8, 1, 5, 6, 2, 9, 0]
Copied!
You can use a mixture of index and negative index together. For example; let's select 2nd element from start until 3rd element from the end. 2nd element has index of 1 (Python starts zero index) and 3rd element from end has index of -2, end index returns the (index - 1), meaning index is bigger by one number.
Code
Output
1
# value 2nd from start until 2nd from the end
2
my_list[1:-2]
Copied!
1
[3, 4, 5, 5, 7, 8, 1, 5, 6, 2]
Copied!

Stride

You can specify a strideβ€”either positive or negative. Stride is added to the square bracket as a second colon :, the stride form will be [start_index : end_index : step]. Step control defines how many elements to skip before selecting next element.
Code
Output
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
my_list[1:7:2] # this will select elements 2nd to 7th every two steps
Copied!
1
[3, 5, 7]
Copied!

List reverse

Python lets you to easily reverse lists
Code
Output
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
my_list[::-1]
Copied!
1
[0, 9, 2, 6, 5, 1, 8, 7, 5, 5, 4, 3, 2]
Copied!

Lists can be nested

A list can contain sublists, which in turn can contain sublists themselves.
A list of lists with their indice
Each element in list or its sublists can be accessed with element index.
Code
Output
1
my_list = ['a', ['b', 'c', 'd'], 'e', [['f', 'g'], 'h'], 'i', 'j']
2
​
3
my_list[3]
Copied!
1
# Returns all sublists in the index number 3
2
[['f', 'g'], 'h']
Copied!
Each sublist adds another square bracket to access its elements. my_list[3][1] returns index 3 of main list and an element at index 1 of the sublist
Simply append another square bracket. All operation of slicing can also be performed on the second square bracket, etc.
Code
Output
1
my_list = ['a', ['b', 'c', 'd'], 'e', [['f', 'g'], 'h'], 'i', 'j']
2
​
3
my_list[3][1]
Copied!
1
# It return index 3 of main list and elements at index 1 of the sublist
2
'h'
Copied!

Lists are mutable

Elements with a list can be deleted, shifted, updated or modified after the list has been created. You can change each element of a list or append new elements to a list.
You can use assignment operator (=) to change an item or a range of items.

Updating a single element

A single value in a list can be replaced by indexing and assignment operator.
Code Index
Output 1
Code Negative Index
Output 2
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
my_list[5] = 2020
Copied!
1
[2, 3, 4, 5, 5, 2020, 8, 1, 5, 6, 2, 9, 0]
Copied!
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
my_list[-3] = 2020
Copied!
1
[2, 3, 4, 5, 5, 7, 8, 1, 5, 6, 2020, 9, 0]
Copied!

Updating multiple elements

Multiple elements can be update by specifying the elements index
Code
Output
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
my_list[5:8] = [2018, 2019, 2020]
Copied!
1
[2, 3, 4, 5, 5, 2018, 2019, 2020, 5, 6, 2, 9, 0]
Copied!

Deleting a single element

An element or elements can be deleted using del keyword.
Code: Delete an element
Output 1
Code: Delete elements
Output 2
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
del my_list[5]
Copied!
1
[2, 3, 4, 5, 5, 8, 1, 5, 6, 2, 9, 0]
Copied!
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
del my_list[3:6]
Copied!
1
[2, 3, 4, 8, 1, 5, 6, 2, 9, 0]
Copied!
First example deletes element [7], second example deletes three elements [5, 5, 7].

Prepending or appending elements to a list

An element or elements can be added to the start or end of a list using the + operator. This is also called concatenation.
Prepend
Append
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
[343, 564] + my_list
4
​
5
# OUTPUT
6
[343, 564, 2, 3, 4, 5, 5, 7, 8, 1, 5, 6, 2, 9, 0]
Copied!
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
my_list + [343, 564]
4
​
5
# OUTPUT
6
[2, 3, 4, 5, 5, 7, 8, 1, 5, 6, 2, 9, 0, 343, 564]
Copied!
If you want to add a single element, we have to wrap it in square brackets []. Otherwise, Python raises a TypeError.
Code
Output
1
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
2
​
3
my_list = 22 + my_list
Copied!
1
TypeError Traceback (most recent call last)
2
<ipython-input-11-57d83415c5aa> in <module>()
3
1 my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
4
2
5
----> 3 my_list = 22 + my_list
6
​
7
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Copied!
The = assignment operator can be used to save the prepending or appending elements.
Prepend
Append
1
# Elements addition
2
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
3
​
4
my_list = [343, 564] + my_list
5
​
6
print(my_list)
7
​
8
#OUTPUT
9
[343, 564, 2, 3, 4, 5, 5, 7, 8, 1, 5, 6, 2, 9, 0]
Copied!
1
# Elements addition
2
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
3
​
4
my_list = my_list + [343, 564]
5
​
6
print(my_list)
7
​
8
#OUTPUT
9
[2, 3, 4, 5, 5, 7, 8, 1, 5, 6, 2, 9, 0, 343, 564]
Copied!
The += augmented assignment operator works only when we append elements to a list
Prepend
Append
1
# Elements addition
2
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
3
​
4
[343, 564] += my_list
5
​
6
#OUTPUT
7
File "<ipython-input-9-3ec7d1771475>", line 3
8
[343, 564] += my_list
9
^
10
SyntaxError: can't assign to literal
Copied!
1
# Elements addition
2
my_list = [2, 3, 4, 5, 5, 7, 8, 1,5, 6, 2, 9, 0]
3
​
4
my_list += [343, 564]
5
​
6
print(my_list)
7
​
8
#OUTPUT
9
[2, 3, 4, 5, 5, 7, 8, 1, 5, 6, 2, 9, 0, 343, 564]
Copied!
The * operator repeats a list for a given number of times.
Code
Ouput
1
my_cities = ['Krakow', 'Warsaw', 'Lodz', 'Kielce']
2
​
3
my_cities * 3
Copied!
1
['Krakow', 'Warsaw', 'Lodz', 'Kielce',
2
'Krakow', 'Warsaw', 'Lodz', 'Kielce',
3
'Krakow', 'Warsaw', 'Lodz', 'Kielce']
Copied!

List methods

list methods modify the target list in place. They do not return a new list. We do not need to use assignment operators such as =.

append()

You can use append() to added an element to the end of a list.
First Tab
Output
1
age = [23, 45, 89, 18, 24, 29, 36]
2
​
3
age.append(57)
Copied!
1
[23, 45, 89, 18, 24, 29, 36, 57]
Copied!
A list can be added to another list, but it will append the list as a sublist rather than extending the elements within the main list (it is added as a single object).
Code
Output
1
age = [23, 45, 89, 18, 24, 29, 36]
2
​
3
age.append([57, 34, 19])
Copied!
1
[23, 45, 89, 18, 24, 29, 36, [57, 34, 19]]
Copied!

extend()

Similar to append(), extend() also adds element/s to the end of a list and only modifies the original list. the argument between () should be an iterable, i.e., adding an element at a time.
Code
Output
1
age = [23, 45, 89, 18, 24, 29, 36]
2
​
3
age.extend([57, 34, 19])
Copied!
1
[23, 45, 89, 18, 24, 29, 36, 57, 34, 19]
Copied!
You can see the difference between append() and extend() methods when adding a list to a list. append() adds as a sublist but extend() adds an element at a time

insert()

You can insert one element at a desired location by using the method insert(). insert() takes two arguments:
  1. 1.
    The index location to add the element and
  2. 2.
    the element (string, float, integer etc).
The newly inserted element will push the elements from the index insert location to the right.
Code
Output
1
['Krakow', 'Warsaw', 'Lodz', 'Kielce']
2
my_cities.insert(2, 'Poznan')
Copied!
1
['Krakow', 'Warsaw', 'Poznan', 'Lodz', 'Kielce']
Copied!

pop()

The pop() removes and returns the last element when no index is provided. You can use pop() with an index to remove element at the given index. pop() is helpful because it may insert or remove an element from only one end, as a result, lists can be implemented as stacks (last-in, first-out).
Code
Output
1
my_cities = ['Krakow', 'Warsaw', 'Warsaw', 'Lodz', 'Kielce']
2
​
3
# pop() returns last element
4
my_cities.pop()
5
​
6
# Above list misses last element
7
print(my_cities)
Copied!
1
# Output for pop()
2
'Kielce'
3
​
4
# Our list after applying pop()
5
['Krakow', 'Warsaw', 'Warsaw', 'Lodz']
Copied!

remove()

You can use remove() method to remove a given element. You have to provide the element (not its index).
Code
Output
1
my_cities = ['Krakow', 'Warsaw', 'Lodz', 'Kielce']
2
​
3
my_cities.remove('Krakow')
Copied!
1
['Warsaw', 'Lodz', 'Kielce']
Copied!
remove() removes only the FIRST occurrence of the element.
Code
Output
1
my_cities = ['Krakow', 'Warsaw', 'Warsaw', 'Lodz', 'Kielce']
2
​
3
my_cities.remove('Warsaw')
Copied!
1
['Krakow', 'Warsaw', 'Lodz', 'Kielce']
Copied!
You can check the Jupyter Notebook in GitHub or Colab.