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

  • enumerate

    Another great utility when working with lists is the enumerate() function. When iterating over list elements, some operations might require the index of those elements. This can be done by iterating over a range(), but a more Pythonic way of doing it is using enumerate():
    names = ['Bob', 'Anna', 'Lily']
    for i in range(len(names)):
    	name = names[i]
    	print(f'Person {i}: {name}')
    names = ['Bob', 'Anna', 'Lily']
    for i, name in enumerate(names):
    	print(f'Person {i}: {name}')
    enumerate() creates a tuple of index and value from each element of a list passed to it. The use of this kind of utility can distinguish good Python code from bad one.

    Challenge

    Given n numbers separated by a space, you are asked to print the sum of their index (starting from 0) and themselves for each number on a single line.
    Can you solve this in a single line 😎?
    Input
    Output
    0 0 0 0
    0 1 2 3
    7 8 4 0 1
    7 9 6 3 5
     
    To check your solution you need to sign in
    Sign in to continue