Python array (list) splice (like JavaScript) 

Joined:
04/09/2007
Posts:
784

April 16, 2014 16:15:27    Last update: April 16, 2014 16:15:27
  1. Create a list, assign it to another variable. They both refer to the same object:
    >>> a = [ 1, 2, 3, 4 ]
    >>> b = a
    >>> a
    [1, 2, 3, 4]
    >>> b
    [1, 2, 3, 4]
    

  2. List comprehension, assign value to a. Now a and b are different:
    >>> a = [ e for e in a if e > 2 ]
    >>> a
    [3, 4]
    >>> b
    [1, 2, 3, 4]
    

  3. Splicing changes list in place, a and b refer to the same object after assignment:
    >>> a = b
    >>> a[:] = [ e for e in a if e > 2 ]
    >>> a
    [3, 4]
    >>> b
    [3, 4]
    >>>
    

Share |
| Comment  | Tags