Sunday 20 December 2020

Python: List comprehensions

 List comprehensions are used to create new lists from other iterables.

 

Syntax

new_list = [expression for_loop_with_one_or_more conditions]

 

Example1: Calculate cubes of numbers

cubes = [value**3 for value in range(1, 11)]

print(cubes)

>>> cubes = [value**3 for value in range(1, 11)]
>>> 
>>> cubes
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>

 

Example 2: Find all the vowels in a string

sentence = 'Hello, How are you'

vowels = [i for i in sentence if i in 'aeiouAEIOU']

>>> vowels = [i for i in sentence if i in 'aeiouAEIOU']
>>> 
>>> vowels
['e', 'o', 'o', 'a', 'e', 'o', 'u']

 

Example 3: Get all even numbers from list of numbers

 

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = [number for number in numbers if number % 2 == 0]

 

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 
>>> even_numbers = [number for number in numbers if number % 2 == 0]
>>> 
>>> even_numbers
[2, 4, 6, 8, 10]

 

You can even use a function in the list comprehension.

>>> def is_even(number):
...   return number % 2 == 0
... 
>>> 
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 
>>> even_numbers = [number for number in numbers if is_even(number)]
>>> 
>>> even_numbers
[2, 4, 6, 8, 10]

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment