Python Both list gets affected after creating list using list2 list1

0 votes

Suppose I have a 

list l1 = [1, 2, 3, 4, 5] 

then I create another list l2 from l1 by

l2 = l1

Now I try to remove 5 from l1.

l1.remove(5)

print(l1)

[1,2,3,4]

but when I see L2 , 5 is removed from l2 also.

print(l2)

[1,2,3,4]

Why 5 is getting removed from l2. 
Is it l2 and l1 sharing the same memory? 
How can we make a list from another list, both sharing different memory address?

Aug 1, 2019 in Python by Praful
3,069 views

1 answer to this question.

0 votes

When you are copying a list to another list using = sign, both the lists refer to the same list object in the memory. So modifying one list, automatically changes the other as they both refer to the same object.

In simple terms, l1 is pointing to the contents of the list one. Then l1 = l2 will just create another pointer to that same list. If you want independent list then you will have to create the list as follows:

list2 = list1[:]
answered Aug 1, 2019 by Lohit

Related Questions In Python

0 votes
1 answer

Creating an empty list in Python

Here is how you can test which ...READ MORE

answered Aug 17, 2018 in Python by Priyaj
• 58,060 points
1,062 views
0 votes
0 answers

Creating a mini language parser using Python

I'm planning to create a simple mini-language ...READ MORE

Dec 27, 2018 in Python by Anirudh
• 2,090 points
947 views
0 votes
1 answer

What is the recommended way to randomize a list of strings using Python?

Hi. Nice question. Here is the simplified answer ...READ MORE

answered Jan 18, 2019 in Python by Nymeria
• 3,560 points
898 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,403 views
0 votes
1 answer
+1 vote
1 answer

How can I reverse list in Python?

Reversing a list is a commonly used ...READ MORE

answered May 13, 2019 in Python by Taj
• 1,080 points
972 views
0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14, 2019 in Python by Junaid
2,199 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP