Produce a list of squared numbers for each number in an iterable range(5).
[x*x for x in range(5)]
Produce a dictionary with keys from an iterable, with key-value pairs of the form (k,2k).
{x : 2*x for x in range(5)}Produce a set of squared numbers for each number in an iterable range(5).
{x*x for x in range(5)}For loop vs List Comprehension:
If your goal is to execute something once for each element in an iterable, throwing away or ignoring any return value, then a _ is the preferred way.
However, if you are interested in transformed output of each element in an iterable, then a _ is the preferred way.
Write a function (join_numbers) that takes a range of integers.
The function should return those numbers as a string, with commas between the
numbers.
That is, given range(15) as input, the function should return this string:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14
nested list comprehensions:
return list of all visited cities, given the dictionary of (country, [cities]) pairs:
all_places_dict = {'USA': ['Philadelphia', 'New York', 'Cleveland', 'San Jose',
'San Francisco'],
'China': ['Beijing', 'Shanghai', 'Guangzhou'],
'UK': ['London'],
'India': ['Hyderabad']}def visited_cities(all_places_dict): return [city for (_,cities) in all_places_dict.items() for city in cities]
Which of the following runs faster?
1. sum([x*x for x in range(100000)])
2. sum((x*x for x in range(100000)))
Second: since it uses generator expression
The generator returns one element at a time, waiting for sum to request the next item in line.
In this way, we’re only consuming one integer’s worth of memory at a time, rather than a huge list of integers’ memory.
produce a list of tuples: (x,y) from range(numrange) where x is odd and y is even.
1. with list comprehension
2. with for loop
print(odd_even_tuples(5))
with list comprehension:
def odd_even_tuples(numrange): return [(x,y) for x in range(1, numrange) if x%2 for y in range(1, numrange) if not y%2]
with for loop:
def odd_even_tuples_via_loop(numrange):
output = []
for x in range(1, numrange):
if x%2:
for y in range(1, numrange):
if not y%2:
output.append((x,y))
return output