Copying the list elements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • psbasha
    Contributor
    • Feb 2007
    • 440

    #1

    Copying the list elements

    Hi,

    I am trying to assign the list elements(l1) to another list (l2).When I am trying to remove the element from l2,it is removing the element from l1.

    Is there any method available to copy the list elements?So that I can avoid deleting the elements.

    Code:
    Sample
    >>> l1 = [1,2,3,4]
    >>> l2 = l1
    >>> l2.remove(3)
    >>> l1
    [1, 2, 4]
    >>> l2
    [1, 2, 4]
    >>>
    O/P :

    I need l1 = [1,2,3,4] and l2 = [1, 2, 4]
    Thanks
    PSB
  • psbasha
    Contributor
    • Feb 2007
    • 440

    #2
    >>> l1 = [1,2,3,4]
    >>> from copy import copy
    >>> l2 = copy(l1)
    >>> l2.remove(3)
    >>> l1
    [1, 2, 3, 4]
    >>> l2
    [1, 2, 4]
    >>>

    The above statement works.But is there any other method available

    -PSB

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by psbasha
      >>> l1 = [1,2,3,4]
      >>> from copy import copy
      >>> l2 = copy(l1)
      >>> l2.remove(3)
      >>> l1
      [1, 2, 3, 4]
      >>> l2
      [1, 2, 4]
      >>>

      The above statement works.But is there any other method available

      -PSB
      >>> l1 = [1, 2, 3, 4]
      >>> l2 = l1[:] # "slice" beginning to end #
      >>> del l1[0]
      >>> l2
      [1, 2, 3, 4]
      >>> l1
      [2, 3, 4]
      >>>

      Comment

      Working...