Lists#
(Click here for the German version of this page)
Lists in general#
A widely used data structure is the “array”. In Python there is a data structure called “list”. Conceptually, they are identical. It is a linear data structure, in which one can store data.
Many other programming languages use curly braces to fill arrays.
Example in C:
int Array_name[] = {1, 2, 3, 4, 5};
Python used square brackets to symbolize lists.
List_name = [1, 2, 3, 4, 5]
In the above example it is never given, that the list consists of integers.
This is due to Python’s dynamic typing. In Python this is not just an integer list, but one can also add other elements of any data type to the same list.
Example:
my_list = [1, 2, 3, 4, 5, "Hello World!"]
In most programming languages this would not be easily possible. This is also not due to the numbers 1 through 5 being implicitly converted to strings to have matching data types. The above list has multiple different data types. One can check this with the function type()
, which was already discussed in the context of dynamic typing in a previous chapter.
Refresher:
The function type(object)
returns the data type or class of the object.
If we call this function for the different elements, by using the usual square brackets to denote access to a given index (starting at 0), then we can observe this:
my_list = [1, 2, 3, 4, 5, "Hello World!"]
print(type(my_list[0]))
# <class 'int'>
# --> Object at index 0 is and integer
print(type(my_list[5]))
# <class 'str'>
# --> Object at index 5 is and string
Therefore, 1
is an integer and ”Hello World!”
is a string.
Reversing lists#
If one wants to reverse a list
nums = [1, 2, 3, 4, 5]
so that the list starts at 5
and ends at 1
, the function reverse()
can be used. The function is similar to sort()
, but instead of sorting, it just reverses the order of the list.
nums = [1, 2, 3, 4, 5]
print(nums)
# --> [1, 2, 3, 4, 5]
nums.reverse()
print(nums)
# --> [5, 4, 3, 2, 1]
Fast initialization of lists#
In case you want to initialize a list with a given amount of a single value, such as a list consisting of 10 zeroes, then you can either the list directly or call append(0)
ten times:
nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
nums = []
for i in range(0, 10): # This loop runs 10 times
nums.append(0)
print(nums)
# --> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Alternatively, there is a shortcut for exactly something like this in Python with the following syntax:
LIST_NAME = [VALUE] * AMOUNT_OCCURENCES
So, for the above example, it would be:
nums = [0] * 10
print(nums)
# --> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Negative indices#
Python has a convenient shortcut for accessing the k-last element in a list (in this case the list is called “num”).
The syntax is: nums[-k]
.
So, with a negative index.
nums[-1]
accesses the last element, nums[-2]
accesses the one before last and so on.
While programming you should pay attention, that negative indices in Python are valid and therefore do not necessarily result in an error.
Length of a list#
To retrieve the length of a list, the function len()
is used, just like when identifying the length of a string.
nums = [1, 2, 3, 4, 5]
print(len(nums))
# --> 5
Append#
To add an element to the back of an already existing list, the append()
method can be used.
nums = [1, 2, 3, 4, 5]
print(nums)
# --> [1, 2, 3, 4, 5]
print(len(nums))
# --> 5
nums.append(6)
print(nums)
# --> [1, 2, 3, 4, 5, 6]
print(len(nums))
# --> 6
One can add as many entries as one wants, since the list is a dynamic data structure, in contrast to arrays in C, where a specific maximum length must be specified.
It is also possible to create empty lists, which can then have values inserted using append()
.
An empty list is initialized as follows:
nums = []
Check whether a list contains a given element#
For this the keyword in
can be used.
x = [1,2,3,4,5]
print(3 in x)
# --> True
# 3 is present in x.
print(42 in x)
# --> False
# 42 is not present in x.
Concatenating lists#
To concatenate two lists, the operator +
can be used. Just like with strings, +
for lists also denotes concatenation:
a = [1, 2, 3]
b = [4, 5, 6]
print(a + b)
# --> [1, 2, 3, 4, 5, 6]
Slicing#
The concept of slicing is utilized to get adjacent sublists. For this, two indices are specified.
To get a subsequence depending on a condition, so called “list comprehension” is used. This is too advanced for this introduction and will not be discussed here. Those who are interested may research that topic themselves.
Back to slicing. An example application would be to get a sublist consisting of all the element after index a
, including a
itself, and before b
, excluding b
itself, or combination of that.
For this, the following syntax is used:
nums[a:b]
The left side of the colon indicates which index should be used as the starting index and the right side indicates which index should not be included. If one wants to leave a side unmodified, one can omit the side.
There are three options for slicing.
Case A:
Sublist up until index b
, not including b
itself.
Here, b
is provided as the first index, which should not be included in the sublist:
nums[:b]
nums = [1, 2, 3, 4, 5]
# index 0 1 2 3 4
print(nums[:3])
# --> [1, 2, 3]
The above example would be identical to nums[0:3]
. Since the left side was omitted, Python knows that the sublist should start at the start of the original list.
It would also be identical to nums[:-2]
, since the index -2
is used to access the second to last element, which is also the element at index 3
.
Case B:
Sublist starting at index a
, including a
itself:
nums[a:]
nums = [1, 2, 3, 4, 5]
# index 0 1 2 3 4
print(nums[2:])
# --> [3, 4, 5]
nums[2:]
is the same as nums[2:len(nums)]
, since the length of the list is the first index, which is not present in the list anymore. If the highest index would be 4
, then capturing the whole list means up until, excluding, 5
.
Case C:
Sublist starting at index a
up until (exclusive) index b
:
nums[a:b]
nums = [1, 2, 3, 4, 5]
# index 0 1 2 3 4
print(nums[1:3])
# --> [2, 3]
Starting from index 1
up until (exclusive) index 3
.
To overwrite the original list with the sublist, the assignment operator can be used.
nums = nums[:-1] # Removes the last element
nums = nums[1:] # Removes the first element
nums = nums[2:-2] # Removes the first two and last two elements
Deleting elements in a list#
To delete specific elements in a list, there are three options.
Option 1:
If the element to be deleted, is located at the start or end of the list, then it can be removed using slicing. Example for deleting the first element of a list:
nums = nums[1:]
The advantage is that you can delete multiple elements if they are at the beginning or at the end. For example, you can use nums = nums[3:]
to delete the first three elements.
Option 2:
You can use the keyword del
to delete a given element. The syntax is the following:
del nums[index_to_be_deleted]
Option 3:
If one want to delete just the last element in the list, one can use the function pop()
:
nums.pop()
You can imagine it as the opposite operation to append()
, which instead of inserting at the back of the list, deletes at the back of the list.
Exercise#
You are given the lists a
, b
, c
und d
.
Your task is to make sure that for the call print(nums)
the specified output appears. You are only allowed to use list slicing and concatenation.
To make it clearer, here is an arbitrary example:
# Output should be: [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = [0, 0, 5, 6, 0]
b = [1, 2, 3, 4, 0, 0, 0]
c = [0, 0, 7, 8, 9]
# One possible solution could be:
nums = b[:4] + a[2:4] + c[2:]
print(nums)
# --> [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Here you can attempt the problem...
# The output should be: [64, 7, 4, 7, 6, 34, 1, 2, 3, 6, 2]
a = [6, 34, 12, 1, 3]
b = [62, 7, 5, 3, 6, 2]
c = [1, 2, 3]
d = [9, 64, 7, 4, 7, 4]
nums = ...
print(nums)
# The output should be:
# [64, 7, 4, 7, 6, 34, 1, 2, 3, 6, 2]
Ellipsis
Solution
a = [6, 34, 12, 1, 3]
b = [62, 7, 5, 3, 6, 2]
c = [1, 2, 3]
d = [9, 64, 7, 4, 7, 4]
# Option 1:
nums = d[1:5] + a[:2] + c + b[4:]
# Option 2 with negative indices:
nums = d[1:-1] + a[:-3] + c + b[-2:]
# A combination of both is also possible.
print(nums)
# --> [64, 7, 4, 7, 6, 34, 1, 2, 3, 6, 2]
It is also possible to concatenate the required elements individually. a[1:2]
is equivalent to a[1]
.
(Index 1
until (excluding) 2
is the same as just index 1
)
Since that would still be slicing, that would be a valid solution.
One could for instance get [64, 7, 4, 7]
using d[1:2] + d[2:3] + d[3:4] + d[4:5]
.
But it is definitely more effort. One more reason, why slicing can be quite convenient.