You are on page 1of 7

2021/5/13 4.1. Lists — Python Notes (0.14.

0)

Python Notes (0.14.0)


P R E VIOUS | N E X T | M O D ULES | I N D EX

4.1. Lists
SEARCH
Contents
Lists Go
Quick example Enter search terms
Difference between append() and extend() or a module, class or
Other list methods function name.
Operators This page: Show
Slicing source.
List comprehension TABLE OF
Filtering Lists CONTENTS
Lists as Stacks 1. Quick Start /
Lists as Queues Tutorial
How to copy a list
2. Variables,
In python, lists are part of the standard language. You expressions,
will find them everywhere. Like almost everything in statements,
Python, lists are objects. There are many methods types
associated to them. Some of which are presented here 1. Iterators
below.
2. Generators

4.1.1. Quick example 3. Exceptions

4. Decorators
>>> l = [1, 2, 3]
>>> l[0] 5. Classes
1
>>> l.append(1) 6. Namespace and
>>> l
scoping rules
[1, 2, 3, 1]
7. Packaging

4.1.2. Difference between append() and 8. Notes about


sorting lists and
extend()
dictionaries
Lists have several methods amongst which the append() 9. Notes about
and extend() methods. The former appends an object to booleans and
the end of the list (e.g., another list) while the later logical operators
appends each element of the iterable object (e.g.,
10. Notes on
anothee list) to the end of the list.
For example, we can append an object (here the
character ‘c’) to the end of a simple list as follows:

>>> stack = ['a','b']


>>> stack.append('c')

https://thomas-cokelaer.info/tutorials/python/lists.html 1/7
2021/5/13 4.1. Lists — Python Notes (0.14.0)

>>> stack
['a', 'b', 'c']

However, if we want to append several objects


contained in a list, the result as expected (or not...) is:

>>> stack.append(['d', 'e', 'f'])


>>> stack
['a', 'b', 'c', ['d', 'e', 'f']]
SEARCH
The object ['d', 'e', 'f'] has been appended to the
exiistng list. However, it happens that sometimes what Go
we want is to append the elements one by one of a Enter search terms

given list rather the list itself. You can do that manually or a module, class or

of course, but a better solution is to use the extend() function name.

method as follows: This page: Show


source.
>>> stack = ['a', 'b', 'c']
>>> stack.extend(['d', 'e','f']) TABLE OF
>>> stack CONTENTS
['a', 'b', 'c', 'd', 'e', 'f']
1. Quick Start /
Tutorial

4.1.3. Other list methods 2. Variables,


expressions,
statements,
4.1.3.1. index
types
The index() methods searches for an element in a list.
For instance: 1. Iterators

2. Generators
>>> my_list = ['a','b','c','b', 'a']
>>> my_list.index('b')
3. Exceptions
1

It returns the index of the first and only occurence of 4. Decorators


‘b’. If you want to specify a range of valid index, you 5. Classes
can indicate the start and stop indices:
6. Namespace and
>>> my_list = ['a','b','c','b', 'a'] scoping rules
>>> my_list.index('b', 2)
3 7. Packaging

Warning 8. Notes about


if the element is not found, an error is raised sorting lists and
dictionaries

9. Notes about
4.1.3.2. insert
booleans and
You can remove element but also insert element
logical operators
wherever you want in a list:
10. Notes on
>>> my_list.insert(2, 'a')
>>> my_list
['b', 'c', 'a', 'b']

The insert() methods insert an object before the index


provided.

https://thomas-cokelaer.info/tutorials/python/lists.html 2/7
2021/5/13 4.1. Lists — Python Notes (0.14.0)

4.1.3.3. remove
Similarly, you can remove the first occurence of an
element as follows:

>>> my_list.remove('a')
>>> my_list
['b', 'c', 'b', 'a']
SEARCH
4.1.3.4. pop
Go
Or remove the last element of a list by using: Enter search terms

>>> my_list.pop() or a module, class or


'a' function name.
>>> my_list
['b', 'c', 'b'] This page: Show
source.
which also returns the value that has been removed.
TABLE OF
CONTENTS
4.1.3.5. count
1. Quick Start /
You can count the number of element of a kind: Tutorial
>>> my_list.count('b') 2. Variables,
2
expressions,
statements,
4.1.3.6. sort types
There is a sort() method that performs an in-place 1. Iterators
sorting:
2. Generators
>>> my_list.sort()
>>> my_list 3. Exceptions
['a', 'b', 'b', 'c']
4. Decorators
Here, it is quite simple since the elements are all
characters. For standard types, the sorting works well. 5. Classes

Imagine now that you have some non-standard types. 6. Namespace and
You can overwrite the function used to perform the scoping rules
comparison as the first argument of the sort() method.
7. Packaging
There is also the possiblity to sort in the reverse order:
8. Notes about
>>> my_list.sort(reverse=True) sorting lists and
>>> my_list
dictionaries
['c', 'b', 'b', 'a']
9. Notes about
booleans and
4.1.3.7. reverse
logical operators
Finally, you can reverse the element in-place:
10. Notes on
>>> my_list = ['a', 'c' ,'b']
>>> my_list.reverse()
>>> my_list
['b', 'c', 'a']

https://thomas-cokelaer.info/tutorials/python/lists.html 3/7
2021/5/13 4.1. Lists — Python Notes (0.14.0)

4.1.4. Operators
The + operator can be used to extend a list:

>>> my_list = [1]


>>> my_list += [2]
>>> my_list
[1, 2]
>>> my_list += [3, 4] SEARCH
>>> my_list
[1, 2, 3, 4]
Go
The * operator ease the creation of list with similar Enter search terms
values or a module, class or
function name.
>>> my_list = [1, 2]
>>> my_list = my_list * 2 This page: Show
>>> my_list source.
[1, 2, 1, 2]
TABLE OF
CONTENTS
4.1.5. Slicing 1. Quick Start /
Tutorial
Slicing uses the symbol : to access to part of a list:
2. Variables,
>>> list[first index:last index:step]
expressions,
>>> list[:]
statements,
>>> a = [0, 1, 2, 3, 4, 5] types
[0, 1, 2, 3, 4, 5]
>>> a[2:] 1. Iterators
[2, 3, 4, 5]
>>> a[:2] 2. Generators
[0, 1]
>>> a[2:-1] 3. Exceptions
[2, 3, 4]
4. Decorators
By default the first index is 0, the last index is the last
5. Classes
one..., and the step is 1. The step is optional. So the
following slicing are equivalent: 6. Namespace and
scoping rules
>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> a[:]
7. Packaging
[1, 2, 3, 4, 5, 6, 7, 8]
>>> a[::1]
8. Notes about
[1, 2, 3, 4, 5, 6, 7, 8]
>>> a[0::1] sorting lists and
[1, 2, 3, 4, 5, 6, 7, 8] dictionaries

9. Notes about
4.1.6. List comprehension booleans and
logical operators
Traditionally, a piece of code that loops over a
sequence could be written as follows: 10. Notes on

>>> evens = []
>>> for i in range(10):
... if i % 2 == 0:
... evens.append(i)

https://thomas-cokelaer.info/tutorials/python/lists.html 4/7
2021/5/13 4.1. Lists — Python Notes (0.14.0)

>>> evens
[0, 2, 4, 6, 8]

This may work, but it actually makes things slower for


Python because the interpreter works on each loop to
determine what part of the sequence has to be
changed.
A list comprehension is the correct answer: SEARCH
>>> [i for i in range(10) if i % 2 == 0]
Go
[0, 2, 4, 6, 8]
Enter search terms
Besides the fact that it is more efficient, it is also or a module, class or
shorter and involves fewer elements. function name.

This page: Show


4.1.7. Filtering Lists source.
TABLE OF
>>> li = [1, 2]
>>> [elem*2 for elem in li if elem>1]
CONTENTS
[4] 1. Quick Start /
Tutorial

4.1.8. Lists as Stacks 2. Variables,


expressions,
The Python documentation gives an example of how to statements,
use lists as stacks, that is a last-in, first-out data types
structures (LIFO).
1. Iterators
An item can be added to a list by using the append()
2. Generators
method. The last item can be removed from the list by
using the pop() method without passing any index to it. 3. Exceptions

>>> stack = ['a','b','c','d'] 4. Decorators


>>> stack.append('e')
>>> stack.append('f') 5. Classes
>>> stack
['a', 'b', 'c', 'd', 'e', 'f'] 6. Namespace and
>>> stack.pop() scoping rules
'f'
>>> stack 7. Packaging
['a, 'b', 'c', 'd', 'e']
8. Notes about
sorting lists and
4.1.9. Lists as Queues dictionaries

Another usage of list, again presented in Python 9. Notes about


documentation is to use lists as queues, that is a first booleans and
in - first out (FIFO). logical operators

>>> queue = ['a', 'b', 'c', 'd'] 10. Notes on


>>> queue.append('e')
>>> queue.append('f')
>>> queue
['a', 'b', 'c', 'd', 'e', 'f']
>>> queue.pop(0)
'a'

https://thomas-cokelaer.info/tutorials/python/lists.html 5/7
2021/5/13 4.1. Lists — Python Notes (0.14.0)

4.1.10. How to copy a list


There are three ways to copy a list:

>>> l2 = list(l)
>>> l2 = l[:]
>>> import copy
>>> l2 = copy.copy(l)
SEARCH
Warning
Don’t do l2 = l, which is a reference, not a copy. Go
Enter search terms
The preceding techniques for copying a list create or a module, class or
shallow copies. IT means that nested objects will not be function name.
copied. Consider this example: This page: Show
source.
>>> a = [1, 2, [3, 4]]
>>> b = a[:] TABLE OF
>>> a[2][0] = 10 CONTENTS
>>> a
[1, 2, [10, 4]] 1. Quick Start /
>>> b Tutorial
[1, 2, [10, 4]]
2. Variables,
To get around this problem, you must perform a deep
expressions,
copy:
statements,
>>> import copy types
>>> a = [1, 2, [3, 4]]
>>> b = copy.deepcopy(a) 1. Iterators
>>> a[2][0] = 10
>>> a 2. Generators
[1, 2, [10, 4]]
>>> b 3. Exceptions
[1, 2, [3, 4]]
4. Decorators

5. Classes
4.1.10.1. Inserting items into a sorted list
The bisect module provides tools to manipulate sorted 6. Namespace and
lists. scoping rules

>>> x = [4, 1]
7. Packaging
>>> x.sort()
>>> import bisect
8. Notes about
>>> bisect.insort(x, 2) sorting lists and
>>> x dictionaries
[1, 2, 4]
9. Notes about
To know where the index where the value would have
booleans and
been inserted, you could have use:
logical operators
>>> x = [4, 1]
>>> x.sort() 10. Notes on
>>> import bisect
>>> bisect.bisect(x, 2)
2

https://thomas-cokelaer.info/tutorials/python/lists.html 6/7
2021/5/13 4.1. Lists — Python Notes (0.14.0)

SEARCH

Go
Enter search terms
or a module, class or
function name.

This page: Show


source.
TABLE OF
CONTENTS
1. Quick Start /
Tutorial

2. Variables,
expressions,
statements,
types

1. Iterators

2. Generators

3. Exceptions

4. Decorators

5. Classes

6. Namespace and
scoping rules

7. Packaging

8. Notes about
sorting lists and
dictionaries

9. Notes about
booleans and
logical operators

10. Notes on

https://thomas-cokelaer.info/tutorials/python/lists.html 7/7

You might also like