0

I'm learning python from datacamp and there is a question puzzles me a lot. Here is the original code, and the task is to: change the element in areas_copy without any change in areas.

Create list areas

areas = [11.25, 18.0, 20.0, 10.75, 9.50]

Create areas_copy

areas_copy = areas

Change areas_copy

areas_copy[0] = 5.0

Print areas

print(areas)

Here is the instruction: You can do this with list() or by using [:] I know how to do that using copy(), but I don't understand the instruction.

Could someone please explain the instruction to me? Thanks

S Yuri
  • 1
  • The instruction is simply telling you can use `list` to create a _copy_ of `areas` elements **or** by using the `[:]` operator which also copy the elements of your array `areas`. So: `areas.copy()` is similar to `list(areas)` and `areas[:]`. I'm saying similar because idk if it is really the same thing, but at least all these ways creates a copy of your array elements without copying the reference to the original array. – Alex Rintt Nov 14 '22 at 03:11
  • Thank you. I'll remember that. Another quick question: does that rule work for dict and set? – S Yuri Nov 14 '22 at 03:31
  • nop, set is not subscriptable, which means you cannot use the `[:]` operator, but you can convert the set to a list using `list(your_set_obj)`, btw you can also use `your_set_obj.copy()`; same applies for dict, avoid using `[:]` because dicts are not index but hash/key based. – Alex Rintt Nov 14 '22 at 03:36

0 Answers0