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

  • Nested list comprehension

    When dealing with 2D lists, it’s also possible to iterate over objects with a list comprehension.
    grid = [
    	[10, 20, 30],
    	[40, 50, 60],
    ]
    squared = [[i * i for i in row] for row in grid]
    print(squared)
    # [[100, 400, 900], [1600, 2500, 3600]]
    Here the outer loop goes over the grid row-by-row. Then we iterate over each item in a row.
    In case we don’t want to have a 2D list as a result, we can flatten out the grid by omitting the inner brackets and moving the for i in row out of the inner loop. We first iterate over the grid with for row in grid and then for i in row:
    grid = [
    	[10, 20, 30],
    	[40, 50, 60],
    ]
    squared = [i * i for row in grid for i in row]
    print(squared)
    # [100, 400, 900, 1600, 2500, 3600]

    Challenge

    Can you use list comprehension to print out all the coordinates of a chessboard? The numbers go from 1 to 8, and the letters are A B C D E F G H. The numbering goes like A1 B1 C1 ... H1 the next line is A2 B2 C2 ... H2, etc. Print each line separately.
    Output
    A1 B1 C1 D1 E1 F1 G1 H1
    A2 B2 C2 D2 E2 F2 G2 H2
    A3 B3 C3 D3 E3 F3 G3 H3
    A4 B4 C4 D4 E4 F4 G4 H4
    A5 B5 C5 D5 E5 F5 G5 H5
    A6 B6 C6 D6 E6 F6 G6 H6
    A7 B7 C7 D7 E7 F7 G7 H7
    A8 B8 C8 D8 E8 F8 G8 H8
    Tip
    You can use a single-line condition to determine if you’re printing a newline as the end parameter of a print method
     
    To check your solution you need to sign in
    Sign in to continue