Table of Contents
How to create a list?
Lists are announced in square brackets [ ]
. The second line of this python list table is the list item index.
z = [3, 7, 4, 2] # Creating a list
In python, lists store an ordered set of elements, which can be of different types. In the example above, the elements are of the same int
type. It is not necessary that all elements be of the same type.
# Creation of a list with different data types
heterogenousElements = [3, True, 'Vitya', 2.0]
This list contains int
, bool
, string
, and float
.
Accessing the items in the list
Each item has an index assigned to it. It is important to note that in python the index of the first element in the list is 0. Item with index 0 (highlighted in blue)
z = [3, 7, 4, 2] # creating a list
# call the first element in the list with index 0
print(z[0])
# item with index 0 -> 3
Negative indexing is also supported. Negative indexing starts from the end. Sometimes it’s more convenient to use it to get the last item in the list, because you don’t need to know the length of the list to access the last item. Item with index -1 (highlighted in blue)
# print the last item
>>> print(z[-1])
2
You can also access the same item using positive indices (as shown below). An alternative way to access the last element in the z
list.
>>> print(z[3])
2
List slice
Slice is good for getting a subset of values from your list. In the example code below, it will return a list with items from index 0 and not including index 2. The first index is written (before : inclusive) and the last (after : ) and not including
# create list
z = [3, 7, 4, 2]
# Outputs items with indexes from 0 to 2 (not including 2)
print(z[0:2])
# output: [3, 7]
# everything but index 3
>>>> print(z[:3])
[3, 7, 4]
The code below returns a list with elements from index 1 to the end.
# from index 1 to the end of the list
>>> print(z[1:])
[7, 4, 2]
Changing items in the list
Lists in Python are modifiable. This means that you can update individual elements of a list after it has been created.
z = [3, 7, 4, 2] # Creating a list
# change the element with index 1 to the string 'fish'
z[1] = 'fish'
print(z)
[3, 'fish', 4, 2]
Methods and Functions of Python Lists
Python lists have different methods that help with programming. This section covers all list methods.
Index Method
The index
method returns the position of the first index, with a value of x
. In the code below, it returns back 0.
# create a list
>>> z = [4, 1, 5, 4, 10, 4]
>>> print(z.index(4))
You can also specify where you start the search from.
>>> print(z.index(4, 3))
3
The count method
The count
method works just as it sounds. It counts the number of times the value appears in the list.
>>> random_list = [4, 1, 5, 4, 10, 4]
>>> print(random_list.count(4))
3
Sort method
Sort the list – the actual code will be: z.sort() The
sort
method sorts and changes the original list.
z = [3, 7, 4, 2]
z.sort()
print(z)
[2, 3, 4, 7]
Sorting the list from the highest to the lowest value The code above sorts the list of numbers from smallest to largest. The code below shows how you can sort the list from largest to smallest.
# Sort and reverse the original list from highest to lowest
z.sort(reverse = True)
print(z)
[7, 4, 3, 2]
Note that you can also sort the list of rows from A to Z (or A-Z) and vice versa.
# Sorting the list with strings
names = ["Steve", "Rachel", "Michael", "Adam", "Jessica", "Lester"]
names.sort()
print(names)
['Adam', 'Jessica', 'Lester', 'Michael', 'Rachel', 'Steve']
Append method
Add value 3 to the end of the list The
append
method adds an item to the end of the list. This happens in place.
z = [7, 4, 3, 2]
z.append(3)
print(z)
[7, 4, 3, 2, 3]
Remove method
The remove method removes the first occurrence of a value in the list.
z = [7, 4, 3, 2, 3]
z.remove(2)
print(z)
The code removes the first occurrence of value 2 from the list z.
[7, 4, 3, 3]
Pop method
z.pop(1) removes the value in index 1 and returns value 4 The
pop
method removes an item in the specified index. This method will also return the element that was removed from the list. In case you didn’t specify an index, it will by default remove the item at the last index.
z = [7, 4, 3, 3]
print(z.pop(1))
print(z)
4
[7, 3, 3]
The Extend method
The
extend method extends
a list by adding items. The advantage over append
is that you can add lists. Add [4, 5]
to the end of z
:
z = [7, 3, 3]
z.extend([4,5])
print(z)
[7, 3, 3, 4, 5]
The same could be done using +
.
>>> print([1,2] + [3,4])
[7, 3, 3, 4, 5]
Insert method
Inserts [1,2] with index 4 The
insert
method inserts an element before the specified index.
z = [7, 3, 3, 4, 5]
z.insert(4, [1, 2])
print(z)
[7, 3, 3, 4, [1, 2], 5]
Simple operations on lists
MethodDescribexin sTrue
if element x
is in the list sx
not in sTrue
if element x
is not in the list ss1
+ s2Combine
list s1
and s2s
* n , n * sCopy
list s
n timeslen(s)
List length s
, i.e. number of elements insmin(s)
Smallest list elementsmax(s)
Largest list element ssum
(s)
Sum of list numbers sfor
i in list()
Go through elements left to right in the for loop Examples of using functions with lists:
>>> list1 = [2, 3, 4, 1, 32]
>>> 2 in list1 # 2 in list1?
True
>>> 33 not in list1 # 33 not in list1?
True
>>> len(list1) # number of list items
5
>>> max(list1) # biggest list item
32
>>> min(list1) # smallest list item
1
>>> sum(list1) # sum of list items
42
# python list generator (list comprehension)
>>> x = [i for i in range(10)]
>>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(list1.reverse()) # expand list
[32, 1, 4, 3, 2]
The +
and *
operators for lists
+
joins two lists.
list1 = [11, 33]
list2 = [1, 9]
list3 = list1 + list2
print(list3)
[11, 33, 1, 9]
* copies the items in the list.
list4 = [1, 2, 3, 4]
list5 = list4 * 3
print(list5)
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Operator in
and not in
The in
operator checks if an item is in the list. If successful, it returns True
, if not, it returns False
.
>>> list1 = [11, 22, 44, 16, 77, 98]
>>> 22 in list1
True
Similarly, not in
returns the opposite result from the in
operator.
>>> 22 not in list1
False
Iterating through a list using the for loop
A list is a sequence. Below is a way that you can use a loop to iterate through all the items in a list.
list1 = [1,2,3,4,5]
for i in list1:
print(i, end=" ")
1 2 3 4 5
Converting a list to a string
How do I convert a list to a string? To convert a list to a string, use the join() method. In Python, it looks like this: ",".join(["a", "b", "c"]) -> "a,b,c"
. The separator is written in quotes before the join, the list must consist of strings. Here are some useful tips for converting a list into a string (or any other iterable, such as tuple
). First, if it is a list of strings, you can simply use join() as follows.
mylist = ['spam', 'ham', 'eggs']
print(', '.join(mylist))
spam, ham, eggs
Using the same method, you can also do the following:
>>> print('\n'.join(mylist))
spam
ham
eggs
However, this simple method does not work if the list contains nonlinear objects, such as integers. If you just want a comma-separated string, you can use this pattern:
list_of_ints = [80, 443, 8080, 8081]
print(str(list_of_ints).strip('[]'))
80, 443, 8080, 8081
Or this one if your objects contain square brackets:
>>>> print(str(list_of_ints)[1:-1])
80, 443, 8080, 8081
Finally, you can use map()
to convert each element to a string list and then join them:
>>> print(', '.join(map(str, list_of_ints)))
80, 443, 8080, 8081
>>> print('\n'.join(map(str, list_of_ints)))
80
443
8080
8081
The Python List Test
How do you create a list? All options are correct l = list[1, 2, 3] l = [1, 2, 3] l = list(1, 2, 3) Continue to What this code will output:
a = [ 1, 342, 223, 'Africa', 'Points'] print(a[-3])
‘Africa’ Error 223 342 Continue to What this code will print:
sample = [10, 20, 30] sample.append(60) sample.insert(3, 40) print(sample)
[10, 20, 30, 60, 40] [10, 20, 30, 40] [10, 20, 30, 40, 60] [60, 10, 20, 30, 40] Continue to What this code will output:
lake = ["Python", 51, False, "22"] lake.reverse() lake.reverse() print(lake[-2])
51 -2 [51] False Continue to Which of the following is true? A list cannot contain nested lists We can insert an item at any position in the list All list items must be of the same type Elements of the list can’t duplicate each other Continue to How to get ['bar', 'baz']
from a list
a = ['foo', 'bar', 'baz', 'qux', 'quux']
? print(a[-4:-3]) print(a[1:-2]) print(a[2:3]) print(a[2:4]) print(a[1], a[2]) Continue to How to get 'bar'
from a list
x = [10, [3.141, 20, [30, 'baz', 2.718]], 'foo']