How to iterate over a list that has duplicate values?

Viewed 1377

This is probably a very basic question but I dont know what I have to search for to find the answer for it:

I have this code:

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

list.append(list[0])

for i in list:
    i.append(0)

print(list)

This List will later be used as coordinates for a curve. I need to duplicate the first coordinate at the end to get a closed curve.

If I then want to add a third value to each coordinate in the list the first and last item in list will be iterated over twice:

[[0, 1, 0, 0], [0, 2, 0], [1, 3, 0], [1, 4, 0], [1, 5, 0], [0, 1, 0, 0]]

I am guessing they have the same memory address and thereby the append-function is applied to the same object at this address once for the first index and once for the last.

What is this phenomenon called ? what is the easiest way to get the list like this:

[[0, 1, 0], [0, 2, 0], [1, 3, 0], [1, 4, 0], [1, 5, 0], [0, 1, 0]]

Thank you for your help

2 Answers

You can do a list comprehension:

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

list.append(list[0])
list = [x + [0] for x in list]

print(list)
# [[0, 1, 0], [0, 2, 0], [1, 3, 0], [1, 4, 0], [1, 5, 0], [0, 1, 0]]

EDIT: The trick here is, using x + [0] within the list comprehension. This way new lists are created, thus you do not append 0 to the same list twice (Hattip to @dx_over_dt)

The problem you have with your approach is, that the first and last element of your list refers to the very same object. You can see this, when you print i and list for every iteration:

for i in list:
     i.append(0)
     print(i)
     print(list)

So for the first and last i in your loop, you will append a 0 to the very same list. You could stick to your approach appending a copy of the first element:

list.append(list[0].copy())

The simplest answer is to add the 0's before appending the closing point.

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

for i in list:
    i.append(0)

list.append(list[0])

print(list)

It's the tiniest bit more efficient than a list comprehension because it's not making copies of the elements.

Related