Prev: The 'list' object | Next: List slicing
spam = list(range(10))
spam
foo = list(range(-10,0,1))
foo
alist = [] # Constructing an empty list here
for i in range(10):
alist.append(i)
alist
zoo = []
for x in range(2):
zoo.append('elephant')
zoo.append('tiger')
zoo.append('zebra')
zoo
chars = []
for code in range(ord('A'), ord('E')):
chars.append(chr(code))
chars
import random as rn
lista=[]
for i in range(10):
lista.append(rn.randint(1,100))
lista
# Fibonacci
flist = []
for i in range(10):
if i < 2:
flist.append(1)
else:
flist.append(flist[i-2]+flist[i-1])
flist
alist = [<expression> <'for' loop defining range of values>]
alist = [i for i in range(10)]
alist
In the above example:
alist = [(2*i**2+3*i) for i in range(1,10,2)]
alist
wordlist = ['Word'+chr(i) for i in range(65,70)]
wordlist
alist = [i%2 for i in range(10)]
alist
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>]
alist = [1 if i%2==1 else 0 for i in range(10)]
alist
alist = ['low' if i<3 else 'mid' if i<7 else 'high' for i in range(10)]
alist
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')
s = '123456789'
alist = [s[i] for i in range(9) if i%2==0]
alist
. Free learning material
. See full copyright and disclaimer notice