By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,768 Members | 2,054 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,768 IT Pros & Developers. It's quick & easy.

Copying the list elements

100+
P: 440
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.

Expand|Select|Wrap|Line Numbers
  1. Sample
  2. >>> l1 = [1,2,3,4]
  3. >>> l2 = l1
  4. >>> l2.remove(3)
  5. >>> l1
  6. [1, 2, 4]
  7. >>> l2
  8. [1, 2, 4]
  9. >>> 
  10.  
O/P :

I need l1 = [1,2,3,4] and l2 = [1, 2, 4]
Thanks
PSB
May 6 '07 #1
Share this Question
Share on Google+
2 Replies


100+
P: 440
>>> 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
May 6 '07 #2

bartonc
Expert 5K+
P: 6,596
>>> 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]
>>>
May 6 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.