fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • Filtering in a list comprehension

    In some cases, we would like to process only specific elements. For instance, we would like to take only strings that have lengths greater than 5 and make them uppercase. To filter only the strings that have lengths greater than 5, we can do that in list comprehension using an if condition:
    locations = ['Maldives', 'Bali', 'Thailand', 'Egypt']
    upper = [place.upper() for place in locations if len(place) > 5]
    print(upper)
    # ['MALDIVES', 'THAILAND']
    This way we only took the places with lengths greater than 5 and created a new list upper with place.upper() elements.

    Challenge

    Given several numbers on a single line, you are asked to calculate the cube of the even ones and ignore the rest.
    The input contains a single line with several integers separated by a space.
    The program should output the cubes of the even numbers from the input.
    Input
    Output
    2 3 9 4 0
    8 64 0
     
    To check your solution you need to sign in
    Sign in to continue