-6

I have a list of lists that contain a list at the end. If this list has more than one element, I want to duplicate the entry and for each with the individual value without being in the list.

E.g.

[[1, [1,2]] -> [[1, 1][1, 2]]

There's probably a much more efficient solution than the one I've tried, but I'd like to understand why you're giving me the mistakes you're giving.

First, even though it indicates that it is not the same list, it is changing the value in both lists. Second, when I create the second element, it changes the previous one as well. Any explanation is welcome. Thanks

Code

output

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
bracaraxp
  • 1
  • 1
  • 2
  • 6
    Please ***don't*** post screenshots of code. Post the code as _text_ (and then highlight it and press `ctrl`+`k` to format it). – gen_Eric Jun 08 '21 at 21:22
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). See [How much research?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). – Prune Jun 08 '21 at 21:49
  • Because *you append the same objects in the original list to the new list* and then *you modify those objects*. – juanpa.arrivillaga Jun 08 '21 at 21:49

2 Answers2

2

Variables in Python are just references. I recommend making a copy by using a slice. l_copy = l_orig[:]

When I first saw the question (pre-edit), I didn't see any code, so I did not have the context. It looks like you're copying the reference to that row. (Meaning it actually points to the sub-lists in the original.)

new_list.append(row[:])
Ben Y
  • 913
  • 6
  • 18
  • Thanks a lot for the answer. I was not seeing that without the [:] I was copying the reference. – bracaraxp Jun 08 '21 at 21:52
  • I guess `.copy()` could have also worked, but I encountered similar issues early on when I started using Python. Just gotta be careful about all those reference things. It's good to know it's not really an assignment. – Ben Y Jun 08 '21 at 22:01
0

Weird right? Look at the following example

lst1 = [1,2,3]
#bad copy example
_
lst2 = lst1
-
lst2.append(4)
print(lst1,lst2)

You would expect that only lst2 should have 4, but no. lst1 and lst2 both have 4.

[1, 2, 3, 4] [1, 2, 3, 4]

So to avoid a problem like this, we can use list2 = list1.copy()

lst1 = [1,2,3]
lst2 = lst1.copy()
lst2.append(4)
print(lst1,lst2)

output

[1, 2, 3] [1, 2, 3, 4]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44