Python list

We already know that a python list can be written as comma-separated values between square brackets and the elements don’t have to be from the same type. Naturally this latter can cause some confusion and errors if you tend to forget about this feature.

>>> [1, 'Python', 3.14]
[1, 'Python', 3.14]

Accessing elements in a python list

Accessing values in a list requires to use their index. Index is the number which was assigned to the element — also called its position. Indexes start with the value of 0. You can access one entry in a list or a range of entries.

>>> a = [1,2,3,4,5]
>>> a[2]
3
>>> a[1:3]
[2, 3]

If you try to access an index which is not filled (it does not hold any value), you get an IndexError.

>>> a = []
>>> a[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

However if you slice a list with indexes which are not present you won’t get an error, just a list with fewer values than you expect (or an empty list of course):

>>> a = [1,2,3,4,5]
>>> a[:7]
[1, 2, 3, 4, 5]
>>> a[6:7]
[]
>>> a[8:]
[]

Adding new elements to a python list

Most of the time you do not have pre-defined values where you can build a list of. That’s why it is essential to add elements to a list.

There are quite some methods. One is to use the append function which appends one element to the end of list. Note that it is one element. Why? You will see soon enough in the examples.

The second method is to use slicing. With this you can add new elements to a list (or replace currently existing ones). In this case you have to use a list as the right-hand-side of the operation. Again, be careful when using this approach because if you slice from the wrong place you can end up losing your current contents.

And if you want to append a list to the end of the list you have to use the extend function which requires an iterable as the parameter — or you can use concatenation. Concatenation is the same as we’ve learned at strings: the plus sign (+).

The best way to insert an element to the beginning of the list is to use slicing with [:0]. This will insert the element(s) at the beginning of the list.

If you have to insert an element somewhere into the list at a given index, use the insert function of the list which takes two parameters: the index where to insert and the object to insert. If the index is occupied by a value then the new object will be inserted before this value at the given index. If the index is not occupied then the object is appended to the list.

>>> a = []
>>> a[0] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.append(2)
>>> a
[2]
>>> a[1:2] = [1]
>>> a
[2, 1]
>>> a[1:3] = [1]
>>> a
[2, 1]
>>> a[1:2] = [3,4,5,6]
>>> a
[2, 3, 4, 5, 6]
>>> a[:] = [2]
>>> a
[2]
>>> a[0:] = [1]
>>> a
[1]
>>> a.extend([2,3,4,5])
>>> a
[1, 2, 3, 4, 5]
>>> a.append([6,7,8])
>>> a
[1, 2, 3, 4, 5, [6, 7, 8]]
>>> a[:0] = [9]
>>> a
[9, 1, 2, 3, 4, 5, [6, 7, 8]]
>>> a[:0] = [10,11,12]
>>> a
[10, 11, 12, 9, 1, 2, 3, 4, 5, [6, 7, 8]]
>>> a += [13,14,15]
>>> a
[10, 11, 12, 9, 1, 2, 3, 4, 5, [6, 7, 8], 13, 14, 15]
>>> a = []
>>> a.insert(2,1)
>>> a
[1]
>>> a.insert(2,2)
>>> a
[1, 2]
>>> a.insert(2,3)
>>> a
[1, 2, 3]
>>> a.insert(2,4)
>>> a
[1, 2, 4, 3]

As you could see, appending a list to a list inserts the whole list to the end — and not the values of the provided list. So take care and use extend in this case.

Updating elements in a python list

As you might know, you can update an element in a list by its index. Again: if you try to access an index which is not currently filled you will get the IndexError.

>>> a = ["Java", "is", "cool!"]
>>> a
['Java', 'is', 'cool!']
>>> a[0] = 'Python'
>>> a
['Python', 'is', 'cool!']

Removing elements from a list

Sometimes you need to remove an element from a list because it is not needed anymore or you just put the wrong element to the place. There are again some methods how to remove elements from a list.

First of all you can use the del statement. As it works for variables it works for whole lists (because they are a variable) and for list elements. Remember, if you delete the list variable you won’t be able to access that list without re-assigning.

Another way is to pop out an element from the list. The pop function takes an optional parameter which is the index to remove. If you do not provide this parameter the last element is removed. The core difference in the usage between del and pop is that pop returns the removed element so you can actually use it.

>>> a = [1, 2, 3, 4, 5, [6, 7, 8]]
>>> a
[1, 2, 3, 4, 5, [6, 7, 8]]
>>> del a[5]
>>> a
[1, 2, 3, 4, 5]
>>> a.pop(3)
4
>>> a.pop()
5
>>> a
[1, 2, 3]

If you want to remove all elements from the list you could re-assign the list with a new empty list or use the clear function of the list.

The difference between these two approaches is that the first one does leave some footprint in the memory and the id of the list changes while clearing the list keeps the id (the memory location).

>>> a = [1, 2, 3, 4, 5, [6, 7, 8]]
>>> id(a)
4335030344
>>> a = []
>>> id(a)
4334935560
>>> b = [1, 2, 3, 4, 5, [6, 7, 8]]
>>> id(b)
4335073672
>>> b.clear()
>>> id(b)
4335073672

Other basic list operations

Two more basic operators on lists you want to use in your programming is determining the length of a list and initializing a list of a given length with given values.

The first problem is well-known, the second one is mostly common when doing dynamic programming or you want to migrate an algorithm from one programming language which uses initialization.

>>> a = [1, 2, 3, 4, 5]
>>> len(a) # returns the length of the given list
5
>>> a = ["Hello!"]*4 # creates a list with the element repeated 4 times
>>> a
['Hello!', 'Hello!', 'Hello!', 'Hello!']

So what next? Lets Learn Python 3 Set. 🙂

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.