hiimarksman
hiimarksman

Reputation: 301

What is wrong with my code here (Python, Lists, Strings)?

I'm iterating through a list "a" with length x, where if column 1 has more than one line break, I want to copy that entire row x and replicate it but has column 1 with a unique value.

For example, if I have a row and column 1 contains values (A, B, C), I want to copy all the other data, and have it only contain 1 value in column 1.

steps = []
temp = a[x]
if a[x][1].count('\n') == 0:
    steps.append(temp)

else:
    split = a[x][1].split('\n')
    count = a[x][1].count('\n')+1
    for b in range(0, count):
        temp[1] = split[b]
        steps.append(temp)

Intended result of list "steps":

xxx, A, yyy, zzz
xxx, B, yyy, zzz
xxx, C, yyy, zzz

Actual result:

xxx, C, yyy, zzz
xxx, C, yyy, zzz
xxx, C, yyy, zzz

Upvotes: 0

Views: 50

Answers (2)

fedest
fedest

Reputation: 1350

That's because Python lists are mutable adn you are always modifying the same list.

When you do:

steps.append(temp)

In each iteration, you are adding the same list (temp) to the result list steps. As in each iteration you are modifying the second element of the list temp when doing

temp[1] = split[b]

The result stepslist, will have each of it's elements (as they are all the same element) modified.

Ilustrated:

Step 1

b = 0
split[b] = A
temp[1] = split[b] -> temp = "xxx, A, yyy, zzz"
steps = [temp] === ["xxx, A, yyy, zzz"]

Step 2

b = 1
split[b] = B
temp[1] = split[b] -> temp = "xxx, B, yyy, zzz"
steps = [temp, temp] === ["xxx, B, yyy, zzz", "xxx, B, yyy, zzz"]

Step 3

b = 2
split[b] = C
temp[1] = split[b] -> temp = "xxx, C, yyy, zzz"
steps = [temp, temp, temp] === ["xxx, C, yyy, zzz", "xxx, C, yyy, zzz", "xxx, C, yyy, zzz"]

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

This question is very hard to understand because you didn't define a or x.

Nevertheless, the problem is almost certainly that you modify and append the same temp dict each time. You need to copy it:

    new_temp = temp.copy()
    new_temp[1] = split[b]
    steps.append(new_temp)

Upvotes: 2

Related Questions