A Python list is a data structure that allows you to store multiple items of potentially different types in a single object. It is a mutable sequence data, so it maintains the order of its items and you can modify specific elements in the list even after its creation. You can access each item in a list by its position. Slicing syntax used for strings is also applicable to lists.
To create a list, you only neeto to enclose the items in square
brackets []
, with commas separating each item. For
example:
my_list = [1, 2.5, "Python", [3, 4]]
print(my_list[0]) # Output: 1
## 1
print(my_list[3][0]) # Output: 3
## 3
print(type(my_list)) # Output: <class 'list'>
## <class 'list'>
In the code lines above, a list object my_list
is
created with four elements: 1
, 2.5
,
"hello"
, [3, 4]
. Observe that the data type of
the elements are all different from each other; 1
is an
integer,
2.5```` is a float,
“Python”is a string, and
[3,
4]``` is another list.
As mentioned earlier, Python lists are mutable. So, for example, you can re-assign another value to replace an existing element of a list as follows:
my_list[3] = "new_value"
print(my_list) # Output: [1, 2.5, "Python", "new_value"]
## [1, 2.5, 'Python', 'new_value']
This behavior is different from some other immutable sequence data, such as strings:
# String is immutable and sequential
my_string = "Hello, World!"
my_string[-6:] = 'Python!'
## TypeError: 'str' object does not support item assignment
print(my_string)
## Hello, World!
Just as a string, to see how many elements a list has, you can use
the len()
function:
len(my_list)
## 4
Note that None
also counts as an element in a list. So,
the length of a list containing it will be like:
my_list[3] = None
print(my_list)
## [1, 2.5, 'Python', None]
len(my_list)
## 4
In Python, the iterables refer to objects whose
elements are accessible one-by-one. A string is an example of the
iterable object. If you pass an iterable in the list constructor,
list()
, Python will access each element of the iterable and
make a list having the elements. For example:
print(my_string)
## Hello, World!
type(my_string)
## <class 'str'>
list(my_string)
## ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
Operations on Python Lists
You can also apply some operations on Python lists:
+
: concatenate two lists*
: concatenate a list multiple times+=
: augmented assignment for lists concatenationdel
: deletes reference of an object1in/not in
: check if there is any matching value in a list
Concatenation of two lists
The +
operator concatenates two lists into a single
list. For example:
a = [1, 2, 3]
b = [4, 5, 6]
print(a + b) # Output: [1, 2, 3, 4, 5, 6]
## [1, 2, 3, 4, 5, 6]
Similarly, the *
operator repeatedly concatenates a list
by a user-specified number of times:
c = [7, 8, 9]
# Output: [7, 8, 9, 7, 8, 9, 7, 8, 9]
print(c * 3)
## [7, 8, 9, 7, 8, 9, 7, 8, 9]
Python also provides augmented assignment operators +=
and *=
that modify a list in place. For example:
d = [11, 23]
e = [91]
# Output: [11, 23, 91]
d += e
print(d)
## [11, 23, 91]
# Output: [11, 23, 91, 11, 23, 91]
d *= 2
print(d)
## [11, 23, 91, 11, 23, 91]
Deleting Object References
In Python, the keyword del
removes its following
reference to an object. When it is applied to a list, it can be used to
delete an item at a specified index or a slice of items. Note that the
del
removes the reference to the object, which may result
in the object being garbage-collected if there are no other references
to it. For example:
apostles = ["Peter", "Andrew", "James", "John", "Philip", "Bartholomew", "Thomas", "Matthew", "James son of Alphaeus", "Jude", "Simon the Zealot", "Judas Iscariot"]
# Deletes the last element of the list
del apostles[-1]
print(apostles)
## ['Peter', 'Andrew', 'James', 'John', 'Philip', 'Bartholomew', 'Thomas', 'Matthew', 'James son of Alphaeus', 'Jude', 'Simon the Zealot']
Membership Operators
The in
operator checks if there is any matching value in
a list (or any other iterable objects). It returns a single Boolean
value if there is at least one element matches to the argument.
The not in
operator negates the in
operator. For example:
ppap = ['p', 'p', 'a', 'p']
'p' in ppap
## True
'p' not in ppap
## False
List Methods
Querying Objects in a List: count
and
index
The count
and index
methods are querying
methods associated with elements inside a list. If you apply the
count()
method to a list, it will return the number of
elements that are matching with the input argument. For example:
fruits = ["apple", "banana", ["strawberry", "persimmon"], "persimmon"]
print(fruits.count("apple")) # Output: 1
## 1
print(fruits.count("persimmon")) # Output: 1
## 1
Note that the count()
method in Python only counts exact
matching items and does not count any items that contain the search
string. For example, if we have a list
["strawberry", "persimmon"]
and search for the value
"persimmon"
, it will not be counted as matching value by
count()
.
The index()
method finds the position of the first
occurrence of a given item in a list. For example:
print(fruits.index("banana")) # Output: 1
## 1
If the item is not found in the list, the index()
method
will raise a ValueError
exception. If you want to avoid
this, use the in
operator mentioned above to check if the
item exists in the list before calling index()
.
fruits = ["apple", "banana", "banana", "pineapple", "grapes", "strawberries"]
fruits.index("mango")
## ValueError: 'mango' is not in list
if "mango" in fruits:
fruits.index("mango")
else:
pass
You can also specify a sublist for the index
method:
list.index(x, start, end)
. Note that end
is
exclusive. For example:
fruits = ["apple", "banana", "banana", "pineapple", "grapes", "strawberries"]
fruits.index("banana", 2, 4)
## 2
fruits.index("pineapple", 2, 4)
## 3
fruits.index("grapes", 2, 4) # ValueError
## ValueError: 'grapes' is not in list
Adding a New Item to a List: append
,
insert
, and extend
The append()
method of a Python list is used to add a
new item at the end of the list. For example:
starter_pokemons = ["Bulbasaur", "Squirtle", "Charmander"]
starter_pokemons.append("Pikachu")
print(starter_pokemons)
## ['Bulbasaur', 'Squirtle', 'Charmander', 'Pikachu']
The insert()
method can insert a new item at a specific
position in the list. This method takes two arguments: the index where
the item should be inserted, and the item itself. For example:
starter_pokemons.insert(0, "Eevee")
print(starter_pokemons)
## ['Eevee', 'Bulbasaur', 'Squirtle', 'Charmander', 'Pikachu']
When you use append()
to add another list to a list, the
new list is added as a single item in the original list. For
example:
charmander_evolution = ["Charmander", "Charmeleon", "Charizard"]
mega_evolution = ["Mega Charizard X", "Mega Charizard Y"]
charmander_evolution.append(mega_evolution)
print(charmander_evolution) # Output: ["Charmander", "Charmeleon", "Charizard", ["Mega Charizard X", "Mega Charizard Y"]]
## ['Charmander', 'Charmeleon', 'Charizard', ['Mega Charizard X', 'Mega Charizard Y']]
If you want to extract each items in a new list and add it to an
existing one, you should use the extend()
method, instead
of append()
. For example:
charmander_evolution.extend(mega_evolution)
print(charmander_evolution)
## ['Charmander', 'Charmeleon', 'Charizard', ['Mega Charizard X', 'Mega Charizard Y'], 'Mega Charizard X', 'Mega Charizard Y']
Deleting an Element in a List: pop
and
remove
The pop()
method returns the last item in a list and
then remove the item from the list. For example, the following Python
code will pop up "toast"
from the
breakfast
.
breakfast = ["bagels", "croissants", "toast"]
breakfast.pop()
## 'toast'
print(breakfast)
## ['bagels', 'croissants']
On the other hand, the remove
method does not return
anything, but you can specify which item to delete from a list.
breakfast.remove("croissants")
print(breakfast)
## ['bagels']
Sorting Items in a List: reverse
and
sort
The reverse()
method reverses the order of the elements
in a list.
primes = [2, 3, 5, 7, 11, 13]
primes.reverse()
print(primes)
## [13, 11, 7, 5, 3, 2]
On the other hand, the sort()
sorts the elements in
ascending order.
primes.sort()
print(primes)
## [2, 3, 5, 7, 11, 13]
It is worth noting that lists are mutable.
Applying any methods, including reverse()
and
sort()
will alter the original list.
To sort character or string items, Python uses ASCII values. The upper cases have lower ASCII values than lower cases. So, when applying sort method, upper cases comes first.
three_fourteen = ["pi", "Pi"]
three_fourteen.sort()
print(three_fourteen)
## ['Pi', 'pi']
List Comprehensions
Python has a really neat feature that’s somewhat distinct from other programming languages, called the list comprehension. It allows you to essentially make a for loop in one line while returning a copy of the list that you’re iterating over.
For example, let’s say you have a list called my_list
with 5 elements, and you want to double each item in the list. By using
a list comprehension, you can achieve this as follows:
my_list = [1, 2, 3, 4, 5]
doubled_list = [2 * item for item in my_list]
print(doubled_list)
## [2, 4, 6, 8, 10]
Since list comprehensions generate a new list, it won’t affect the
original list object. So my_list
will remain unchanged:
print(my_list)
## [1, 2, 3, 4, 5]
You can also use list comprehensions to filter or call functions on
each item of a list. For example, let’s say you have a list called
my_list
with 100 numbers, and you want to create a new list
containing only the numbers that are multiples of 10:
my_list = list(range(100))
filtered_list = [item for item in my_list if item % 10 == 0]
print(filtered_list)
## [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
This will create a new list called filtered_list that only contains the numbers that are multiples of 10.
It is not exclusive to lists, and works the same for the other objects.↩︎