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 in Python by Praful
11 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 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
• 56,900 points
73 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,070 points
61 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 in Python by Nymeria
• 3,520 points
54 views
+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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 283 views
+1 vote
1 answer

How can I reverse list in Python?

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

answered May 13 in Python by Taj
• 1,040 points
41 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 in Python by Junaid
37 views