<jupyter_start><jupyter_text>Python in Action Part 1: Python Fundamentals 29 &mdash; List comprehensions in Python> a more functional way to create lists List comprehensions allow you to create lists in Python in a very concise and terse way.Initially, they might seem to be more difficult to read than its *imperative* counterpart, but over the time you will see that it is clearer and more efficient.Let's see an example. Suppose we need to compute the power of two of a list of numbers:<jupyter_code>numbers = range(0, 6)
numbers_power_2 = []

for n in numbers:
    numbers_power_2.append(n ** 2)

print(numbers)<jupyter_output>range(0, 6)<jupyter_text>When using list comprehensions, it becomes clearer and more *functional*:<jupyter_code>numbers = range(0, 6)

numbers_power_2 = [n ** 2 for n in numbers]
print(numbers_power_2)
And also clearer than using `map()`:
numbers = range(0, 6)

numbers_power_2 = list(map(lambda n : n ** 2, numbers))
print(numbers_power_2)<jupyter_output>[0, 1, 4, 9, 16, 25]<jupyter_text>List comprehensions support nested for loops too:<jupyter_code>months = ['January', 'February', 'March']
years = [2019, 2020, 2021]

combination = [ m + ', ' + str(y) for y in years for m in months]

print(combination) # ['January, 2019', 'February, 2019', ...]<jupyter_output>['January, 2019', 'February, 2019', 'March, 2019', 'January, 2020', 'February, 2020', 'March, 2020', 'January, 2021', 'February, 2021', 'March, 2021']<jupyter_text>You can also use list comprehensions and nested loops to create list of lists:<jupyter_code>months = ['January', 'February', 'March']
years = [2019, 2020, 2021]

list_of_lists_combination = [[m + ', ' + str(y) for y in years] for m in months]

print(list_of_lists_combination)<jupyter_output>[['January, 2019', 'January, 2020', 'January, 2021'], ['February, 2019', 'February, 2020', 'February, 2021'], ['March, 2019', 'March, 2020', 'March, 2021']]<jupyter_text>Some additional use cases for list comprehensions when using nested loops:<jupyter_code>some_tuples = [(x, i) for x in range(-1, 6) for i in [0, 1]]
print(some_tuples) # [(-1, 0), (-1, 1), (0, 0), (0, 1)...]<jupyter_output>[(-1, 0), (-1, 1), (0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1), (4, 0), (4, 1), (5, 0), (5, 1)]
{'fraction_non_alphanumeric': 0.15789473684210525, 'fraction_numerical': 0.07607253427686864, 'mean_word_length': 5.633431085043989, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '651083', 'license': 'MIT', 'n_tokens_mistral': 973, 'n_tokens_neox': 768, 'n_words': 285, 'path': '01-python-basics/29-list-comprehensions.ipynb', 'repo_name': 'sergiofgonzalez/python-in-action', 'size': '2261'}