Prev: The 'list' object       |       Next: List slicing

# List construction¶

• Three major ways to construct a list are explained below. Learn them all and apply -whenever possible- list comprehension.

## (1) list & range()¶

• range() returns a sequence which is not yet a list.
• Passing a range() as argument in a list() constructor method constructs a list object.
In [1]:
spam = list(range(10))
spam

Out[1]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]:
foo = list(range(-10,0,1))
foo

Out[3]:
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]

## (2) append()¶

• append() is a list method adding a new list element at the end of the list
• A list is created by appending new elements in an empty list; usually this is done in a for loop
• Note that you need first to construct an empty list
In [1]:
alist = []       # Constructing an empty list here
for i in range(10):
alist.append(i)

alist

Out[1]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [10]:
zoo = []
for x in range(2):
zoo.append('elephant')
zoo.append('tiger')
zoo.append('zebra')

zoo

Out[10]:
['elephant', 'tiger', 'zebra', 'elephant', 'tiger', 'zebra']
In [12]:
chars = []
for code in range(ord('A'), ord('E')):
chars.append(chr(code))

chars

Out[12]:
['A', 'B', 'C', 'D']
In [14]:
import random as rn

lista=[]
for i in range(10):
lista.append(rn.randint(1,100))
lista

Out[14]:
[71, 95, 58, 20, 61, 51, 99, 57, 15, 83]
In [24]:
# Fibonacci

flist = []
for i in range(10):
if i < 2:
flist.append(1)
else:
flist.append(flist[i-2]+flist[i-1])

flist

Out[24]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

## (3) List comprehension¶

• In list comprehension we describe the set of the elements that the list contains
• Essentially a 'comprehension' is a set of looping and filtering instructions (see python documentation here)
• The simple form of a list comprehension is:
   alist = [<expression> <'for' loop defining range of values>]
In [26]:
alist = [i for i in range(10)]
alist

Out[26]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above example:

• The expression is 'i' describing the form of the elements
• The loop is 'for i in range(10)' describing a loop of 10 iterations where i takes the values from 0 to 9.
• Overall, the list comprehension describes a list with elements of form 'i' returned by the 'for-range' loop.
In [29]:
alist = [(2*i**2+3*i) for i in range(1,10,2)]
alist

Out[29]:
[5, 27, 65, 119, 189]
In [14]:
wordlist = ['Word'+chr(i) for i in range(65,70)]
wordlist

Out[14]:
['WordA', 'WordB', 'WordC', 'WordD', 'WordE']
In [35]:
alist = [i%2 for i in range(10)]
alist

Out[35]:
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

#### Conditional expressions in comprehensions¶

• Comprehensions may include conditional expressions. This allows to construct lists in a more complex and efficient manner
• Recall that a conditional expression is of the form:

   <expression_True> <if_condition> <expression_False>
• Thus, a list comprehension can be written as follows:

   alist = [<conditional expression> <'for' to define range of values>]
In [3]:
alist = [1 if i%2==1 else 0 for i in range(10)]
alist

Out[3]:
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
• 'elif' branches can not be used in list comprehensions but the same result is obtained using nested if-else
In [2]:
alist = ['low' if i<3 else 'mid' if i<7 else 'high' for i in range(10)]
alist

Out[2]:
['low', 'low', 'low', 'mid', 'mid', 'mid', 'mid', 'high', 'high', 'high']
• Compare the above list comprehension to the typical if command:

  for i in range(10):
if i<3:
print('low')
else:
if i<7:
print('mid')
else:
print('high')
• if the else clause is missing then the 'if condition' should be placed at the end of the comprehension after the for loop, as in the example below:
In [24]:
s = '123456789'
alist = [s[i] for i in range(9) if i%2==0]
alist

Out[24]:
['1', '3', '5', '7', '9']

. Free learning material
. See full copyright and disclaimer notice