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

  • Combining zip and enumerate

    Sometimes, we might want to know the indices for zipped lists. In that case, we can use enumerate() on top of zip(). Yet, it’s essential to understand what each of those functions does. Zip returns a tuple for each element pair of list elements. Enumerate returns a tuple for each element of a list. Therefore the resulting structure will be tuple of tuples:
    a = [1, 2, 3, 4]
    b = [5, 6, 7, 8]
    zip(a, b)             # [(1, 5), (2, 6), (3, 7), (4, 8)]
    enumerate(a)          # [(0, 1), (1, 2), (2, 3), (3, 4)]
    enumerate(b)          # [(0, 5), (1, 6), (2, 7), (3, 8)]
    enumerate(zip(a, b))  # [(0, (1, 5)), (1, (2, 6)), (2, (3, 7)), (3, (4, 8))]
    
    # Therefore, we need to loop over the elements with tuples:
    for i, (item1, item2) in enumerate(zip(a, b)):
    	print(f'index: {i} => a[i]={item1} and b[i]={item2}')
    
    # index: 0 => a[i]=1 and b[i]=5
    # index: 1 => a[i]=2 and b[i]=6
    # index: 2 => a[i]=3 and b[i]=7
    # index: 3 => a[i]=4 and b[i]=8
    Notice how item1 and item2 are wrapped to form a tuple, in the for loop.

    Challenge

    Given 3 lists each on a separate line, you are asked to create a new list from those which will represent the sum of the elements of the 3 lists, while skipping the values at odd locations (indexing starts at 0).
    The input contains 3 lines - each one contains numbers separated by a space.
    The program should print a single line - the resulting list.
    Input
    Output
    1 2 3 4 5 6 7 8 9 10 11 12
    15 21
    Can you solve this in a single line 😎?
     
    To check your solution you need to sign in
    Sign in to continue