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

  • Operations on lists

    Just like we could add two strings together or multiply a string by a number, we can do those operations for lists as well. We can add two lists together, which will result in a concatenation of the two. We can multiply a list by an integer n, which will repeat the list n times.
    l1 = [1, 'abc']
    l2 = [2, 'def']
    print(l1 + l2)      # [1, 'abc', 2, 'def']
    print(l1 * 5)       # [1, 'abc', 1, 'abc', 1, 'abc', 1, 'abc', 1, 'abc']
    We can even modify the list in place with +=:
    l1 = [1, 'abc']
    l2 = [2, 'def']
    l1 += l2
    print(l1)      # [1, 'abc', 2, 'def']
    print(l2)      # [2, 'def']
    To initialize a list of numbers with size n, we can simply multiply [0] by n:
    n = 10
    l = [0] * n
    print(l)     # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    l[1] = 7
    print(l)     # [0, 7, 0, 0, 0, 0, 0, 0, 0, 0]

    Challenge

    Given two integers x and n, your task is to define an array of n elements filled with x as an initial value.
    Input
    Output
    10 2
    [10, 10]
     
    To check your solution you need to sign in
    Sign in to continue