List¶
author: Parin Chaipunya affil: KMUTT
What is a list ?¶
A list is a collection of items that are putted together inside a pair of square brackets, separated by commas.
[1, 2.0, "three"] # without storing
[1, 2.0, 'three']
L = [1, 2, "three"] # stroing into a variable
print(L) #printing the whole list.
[1, 2, 'three']
L = [1, 2, 3, [1, 2, 3]]
print(L)
[1, 2, 3, [1, 2, 3]]
Accessing an entry¶
Forward indexing¶
Entries of a list is indexed with integers starting with 0. An entry can be called by its parent list followed by its index within the square brackets.
Therefore, the above list L
could be seen as L = [L[0], L[1], L[2]]
.
From the above list L
, we print each entry in the following block.
print(L[0])
print(L[1])
print(L[2])
1 2 3
Backward indexing¶
An entry can be accessed with a backward index.
Here, the last entry is indexed -1
, the second last entry is indexed -2
, etc.
print(L[-1])
print(L[-2])
print(L[-3])
[1, 2, 3] 3 2
List operations¶
One could play around with lists, which includes
- adding entries to a list
- removing an entry from a list.
Adding entries to a list¶
One could concatenate two lists using +
.
L1 = [1, 2.0, "three"]
L2 = [4, "FIVE"]
LL = L1 + L2
print(LL)
[1, 2.0, 'three', 4, 'FIVE']
LLL = L2 + L1
print(LLL)
[4, 'FIVE', 1, 2.0, 'three']
print(LLL)
[4, 'FIVE', 1, 2.0, 'three']
One could repeat the list any number of times by using *
.
3*L2 # the number that multiplies here must be an integer.
[4, 'FIVE', 4, 'FIVE', 4, 'FIVE']
A remark here is that a list of numbers is not an equivalence of a vector in mathematics. As we see above, we cannot add or multiply a scalar to do algebra.
Removing entries from a list¶
If a specific value is to be removed from a list, we use a list's method .remove()
.
By default, it removes the first match.
L = [1, 2.0, "three", 2.0, 1]
print(L)
[1, 2.0, 'three', 2.0, 1]
L.remove(1)
print(L)
[2.0, 'three', 2.0, 1]
To remove an entry at a specific index, we may use del
or to use a list's method .pop()
.
del L[1]
print(L)
[2.0, 2.0, 1]
L.pop(-1)
print(L)
[2.0, 2.0]
To remove all entries matching some conditions, we may use the following trick.
L = [1, 2, 3, 2, 1]
print(L)
[1, 2, 3, 2, 1]
[x for x in L if x != 2]
[1, 3, 1]
Slicing¶
Slicing refers to the extraction of some entries (usually multiple ones) from a list.
The main tool to use is :
.
i:j
¶
From a list L
, we use the slice L[i:j]
to extract a list [L[i], L[i+1], ..., L[j-1]]
.
Note that i:j
starts at i
and ends at j-1
, excluding the j
index.
L = [1, 2, 3, 4, 3, 2, 1]
print(L[2:5])
[3, 4, 3]
i:
and :j
¶
From a list L
, the slice L[i:]
generates the list [L[i], L[i+1], ..., L[-1]]
.
Likewise, the slice L[:j]
generates the list [L[0], L[1], ..., L[j-1]]
.
print(L[2:])
print(L[:4])
[3, 4, 3, 2, 1] [1, 2, 3, 4]