Lists in Python

A quick introduction to working with lists in Python.

Lists are a general container in Python. Lists are a sequence-type of data structure that can be growns and reduced in size dynamically, i.e. as needed during your program.

Lists are sortable.

We can declare a list with square brackets []. Accessing a single element from within a list is done by using the square brackets and entering desired index location.

# this is a empty list
a = []
print(a)
[]
# this is a list with elements of type integer
b = [1,2,3]
print(b)
[1, 2, 3]
# this is a list with elements of different basic data types
c = [1, 1.2, "text"]
print(c)
[1, 1.2, 'text']
# lets check the data types of the list c, and its elements
type(c)
list
type(c[0])
int
type(c[1])
float
type(c[2])
str

As can be seen from above example list indexing starts at 0.

The lists shown above have 1 dimension – but a list can have multiple dimensions. This is done by storing lists inside lists. He is an example of a list with 2 dimensions:

d = [[1,2],[3,4]]
d[0]
[1, 2]

Using the first set of square brackets allows controlling the first dimension. In this case the first row of the two dimensional matrix accessed.

Below, I acces first element in first row.

d[0][0]
1

A list is an object in itself. This is why I can put a list inside another list. And that list could have another list inside itself. And so on. But, I can also have different levels inside my list.

Below is an example where first element is 3 levels deep, the second element is 2 levels deep and the third element has only its first level:

e = [[[1,4],[3,6]],[1,2,3],"abcdefg"]
# accessing first element from lowest level of first element in list "e"
e[0][0][0]
1
# accessing first element from lowest level of second element in list "e"
e[1][0]
1
# accessing third element in list "e", which has no further levels below it
e[2]
'abcdefg'

In my last comment I wrote that the last element in list “e” has no further levels. It is actually not 100% true since a string itself is a sequence and its characters can thus be accessed in similar way as elements in a list:

e[2][2]
'c'

Index -1 indicates the last index in a list:

e[-1]
'abcdefg'

Index -2 indicates second last index in a list:

e[-2]
[1, 2, 3]
# another example, a going one level deeper
e[-2][-2]
2

-3 indicates third last index in list, and so on and so forth:

e[-3][1][-2]
3

Lists can be merged, using the + operator:

[1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]

This also means that I cannot conduct elementwise mathematical operations by using operators such as + or -. For this I would have to delcare arrays in NumPy (a Python module).

Lists have a series or handy methods. I demonstrate all of them in the remaining lines of this post!

append() appends something to the end of a list

f = [1,2,3]
f.append("text")
print(f)
[1, 2, 3, 'text']

extend() enables extending a list with another list

g = [1,2,3]
g.extend([4,5,6])
print(g)
[1, 2, 3, 4, 5, 6]

insert() enables inserting an element at specified index in a list

h = [1,2,3]
h.insert(0,"prefix")
print(h)
['prefix', 1, 2, 3]
h.insert(4,"postfix")
print(h)
['prefix', 1, 2, 3, 'postfix']

remove() remoces an element from a list; remove() only removes first match

h.remove("postfix")
print(h)
['prefix', 1, 2, 3]
i = [1,1,1,2,2,2]
i.remove(1)
print(i)
[1, 1, 2, 2, 2]

index() returns smallest index of a match in a list

j = [1,2,3,3,3,4,5,6,1]
j.index(1)
0

count() returns the number of matches within a list

j.count(3)
3
j.count(6)
1

pop() returns and removes last element in a list; or at given index

k = [1,2,3,4,5]
k.pop()
5
print(k)
[1, 2, 3, 4]
k.pop(2)
3
print(k)
[1, 2, 4]
k.pop(-2) # pops second last element in list
2
print(k)
[1, 4]

reverse() reverses list order

# reverse() reverses a list
l = ["a","b","c","d"]
l.reverse()
print(l)
['d', 'c', 'b', 'a']

in Python 3+ .cop() returns a shallow copy of the list

m = l.copy()
print(m)
['a', 'b', 'c', 'd']

clear() clears a list from all its elements

# clear() clears a list
m.clear()
print(m)
[]
print(l)
['d', 'c', 'b', 'a']

There are many functions that are not list methods but can be used on lists

any(): takes a list (or any other iterable) and returns True if at least one element is True

any([1,2,3])
True
any([2,2,2])
True
any([0,-1])
True
any([0,0])
False
any(["text","book"])
True
any("text")
True
any("false")
True
any([True,False,False])
True

all() returns True if all elements in a list are True

all([1,0])
False
all([1,1])
True

ascii() returns printable notation of list

ascii(["!!?%&!","å","ø"])
"['!!?%&!', '\\xe5', '\\xf8']"

enumerate() returns index to an iterable object, and returns the object including indexing

m = enumerate("text",start=0)
for letter in m:
    print(letter)
(0, 't')
(1, 'e')
(2, 'x')
(3, 't')
# enumerate returns a tuple for every element of the iterable,containing (index, element)
l.reverse()
for i in enumerate(l,start=0):
    if i[0] > 1:
        print(i)
(2, 'c')
(3, 'd')
print(l)
['a', 'b', 'c', 'd']
print(enumerate(l,start=2))
<enumerate object at 0x000002141DDAE0E8>

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Close

Meta