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

  • append

    We’ve seen how to modify a list by concatenating another one to it. What if we would like to modify a list by adding a single value. One option would be to add a value wrapped in a list but python has a dedicated way of doing it with .append():
    l = [12, 54, 'hello']
    l += [38]
    print(l)    # [12, 54, 'hello', 38]
    l = [12, 54, 'hello']
    l.append(38)
    print(l)    # [12, 54, 'hello', 38]
    We can declare an empty array in the beginning and add elements one by one with append:
    l = []
    l.append('Hi')
    l.append('this')
    l += ['is', 'the', 'number']
    l.append(42)
    print(l)       # ['Hi', 'this', 'is', 'the', 'number', 42]

    Challenge

    Declare an empty list and add 7 integers read from the input with append.
    Change each element by replacing it with its square.
    Print the resulting list in the output.
    Input
    Output
    1 2 3 4 5 6 7
    [1, 4, 9, 16, 25, 36, 49]
     
    To check your solution you need to sign in
    Sign in to continue