Brainstorming 05: Mastering Python List Comprehension

 Easy:

  1. Create a list comprehension to generate a list of squares for numbers from 1 to 10.

  2. Write a list comprehension to filter out all the even numbers from a list of integers between 1 and 20.

  3. Generate a list of first 10 multiples of 3 using list comprehension.

  4. Create a list comprehension that extracts all the vowels from a given string.

  5. Use a list comprehension to convert a list of Celsius temperatures to Fahrenheit.

Medium:

    6.  Filter prime numbers between 1 and 50:
         Output:  [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
    

    7. FizzBuzz (replace multiples of 3 with "Fizz" and multiples of 5 with "Buzz"):
        Output:  [1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14,
                        'FizzBuzz', 16, 17, 'Fizz', 19, 'Buzz']


    
8. Generate a list of all the words in a sentence that have more than 3 letters using a list comprehension.
        Output: ['List', 'comprehensions', 'powerful', 'concise']

    9. Create a list of tuples using list comprehension where each tuple contains a number and its cube, for numbers from 1 to 10.
        Output:  [(1, 1), (2, 8), (3, 27), (4, 64), (5, 125), (6, 216), 
                        (7, 343), (8, 512), (9, 729), (10, 1000)]

    10. Write a list comprehension that takes a list of integers and produces another list where each element is doubled if it's even, and halved if it's odd. 
        Output: [0.5, 4, 1.5, 8, 2.5, 12, 3.5, 16, 4.5, 20]

Hard:

    11. Generate all Pythagorean triples up to 20:
          Output: [(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15), (12, 16, 20)]

    12. Create a list comprehension that extracts the common elements from two lists of integers.
    
    13. Reverse order of words longer than 4 characters:
            Output: ['comprehension', 'powerful'] -> ['noisneherpmoc', 'lufrewop']

    14. Generate pairs (x, y) where x < y (1 to 5):
            Output: [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
 
    15. Use a list comprehension to flatten a 2D list (matrix) into a 1D list.


Previous Post Next Post