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

  • list methods

    Similar to strings, lists also have many utility methods. Yet, if string methods don’t modify the initial string and return a new one, list methods make changes to the initial list itself.
    Method
    Description
    Examples
    Results
    Alternative
    count(x)
    Count the number of occurrences of x
    l.count(0)
    3
    -
    clear()
    Make the list empty
    l.clear()
    -
    l = [] del l[:] l *= 0
    copy()
    Copy and return the list
    new = l.copy()
    -
    new = l[:] new = list(l) new = copy.copy(l)
    index(x)
    Find the first occurrence of x (ValueError if not in the list)
    l.index(0)
    5
    -
    insert(pos, x)
    Insert x at position pos
    l.insert(1, 7)
    [1, 7, 1]
    l = l[:pos] + [x] + l[pos:]
    remove(x)
    Remove x from the list
    l.remove(7)
    [1, 1]
    -
    reverse()
    Reverse the list
    l.reverse()
    -
    l = l[::-1]
    sort()
    Sort the list in increasing order
    l.sort()
    -
    l = sorted(l)
    Again, most of the names are very intuitive. Yet, it’s not mandatory to remember them all. A quick googling will give you the needed results. These examples are for demonstration purposes. To show what is possible with Python lists.

    Challenge

    Given n numbers, you are asked to sort them in ascending order and print them in the output.
    The first line of the input contains a single number n. The next n lines contain integers each on a separate line.
    The program should output all the numbers on a single line in increasing order separated by a space.
    Input
    Output
    5 1 4 3 0 -1
    -1 0 1 3 4
     
    To check your solution you need to sign in
    Sign in to continue