About changing an element in a list

hello, i want to know how it’s possible to change an element in a list without assigning anything to it !!!
exg :
list = [1, 2, 3, 4, 5]

list02 = list 

list02[0] = 6

print (list)

》》》》》》》[6, 2, 3, 4, 5]

i didn’t assign anything “list” but the first element has changed from 1 to 6

When you write this:

list02 = list01

that does not make list02 a copy of list01. It makes list02 a

second name for the same object as list01.

Since “list01” and “list02” are both names for the same list, it doesn’t

matter which name you use to modify the list, the effect is the same.

In Python, assignment:

name = object

does not make a copy.

To make a copy of the list, you can use:

# Slicing.

list02 = list01[:]



# Copy method.

list02 = list01.copy()



# The list constructor.

list02 = list(list01)



# Copy module, shallow copy.

import copy

list02 = copy.copy(list01)



# ... or a deep copy.

list02 = copy.deepcopy(list02)



# For-loop.

list02 = []

for item in list01:

    list02.append(item)

and probably other ways as well. The fastest for small lists is probably

slicing, but I haven’t timed it. For huge lists, the first three are

probably more or less the same.

2 Likes

Thanks a lot Mr. steven. now it’s making sense :relaxed: