Francais

Francais


Home


Products


Download


Tutorials

    Python Section
  • Python Quick Reference

  • Web Ring/Links


    Contact

    List Operations

    Replace element(s)

    Differently from string, a list can be modified. A list's element is identified with the array syntax, in other words, with the same syntax as for the string. An assignment can replace one or more items at once.

    Examples :
    Replace an element Replace several elements
    >>> list=[ 1, 2, 3, 4]
    >>> list[0]=5
    >>> print list
    [5, 2, 3, 4]
    >>> list=[ 1, 2, 3, 4]
    >>> # Replace the two firsts
    >>> list[0:2]=[5, 6]
    >>> # Replace the 4th and add a 5th.
    >>> list[4:2]=[7, 8]
    >>> print list
    [5, 6, 3, 4, 7, 8]

    Remove element(s)

    Even list's elements can be removed. That is done by assigns a empty list to the element.

    Examples :
    Remove 1 element the third Remove 2 elements the third and fourth
    >>> list=[1, 2, 3, 4, 5]
    >>> list[2:3]=[]
    >>> print list
    [1, 2, 4, 5]
    >>> list=[1, 2, 3, 4, 5]
    >>> list[2:4]=[]
    >>> print list
    [1, 2, 5]
    Remove all elements after the fourth Suppress from the first element up to the second.
    >>> list=[1, 2, 3, 4, 5]
    >>> list[3:]=[]
    >>> print list
    [1, 2, 3]
    >>> list=[1, 2, 3, 4, 5]
    >>> list[:2]=[]
    >>> print list
    [ 3, 4, 5]

    Add or concatenate elements

    The append() function adds element at the end of the list. Be care, how the list variable was initialized. See chapter Assign several variables in the same time.

    Examples :
    Simple assignment Multiple assignment Assignment remove the link
    >>> A=[]
    >>> B=[]
    >>> A.append(1)
    >>> B.append(2)
    >>> print A, B
    [1] [2]
    >>> A=B=[]
    >>> A.append(1)
    >>> B.append(2)
    >>> print A, B
    [1, 2] [1, 2]
    >>> A=B=[]
    >>> A=[3]
    >>> A.append(1)
    >>> B.append(2)
    >>> print A, B
    [3, 1] [2]
    Add element can be done by addition.

    Examples :
    Simple assignment Multiple assignment Assignment remove the link
    >>> A=[]
    >>> B=[]
    >>> A+=[1]
    >>> B+=[2]
    >>> print A, B
    [1] [2]
    >>> A=B=[]
    >>> A+=[1]
    >>> B+=[2]
    >>> print A, B
    [1, 2] [1, 2]
    >>> A=B=[]
    >>> A=[3]
    >>> A+=[1]
    >>> B+=[2]
    >>> print A, B
    [3, 1] [2]



    Previous Page
    6/13

    Next Page