In [ ]:
# list comprehensions are expressions notated with [] that build lists using iteration
In [2]:
# if you just want to make a list from an iterable, use list()
a = list('fish')
a[1] = 'o'
a
Out[2]:
In [5]:
# if you want to do some operation on the iteration variable, use list comprehensions
[x + '!' for x in 'fish']
Out[5]:
In [7]:
# list comprehensions support if for conditional inclusion in result
[4 for x in 'fish' if x != 'i']
Out[7]:
In [10]:
# you can also use for/in and append to construct cases that would not be possible
# with list comprehensions
result = []
for x in 'fish':
if x != 'i':
result.append(x)
result.append('foo')
result
Out[10]:
In [ ]:
# if your list comprehension is too long, consider for/append instead