1

Hopefully not too basic of a Python question, but I stumbled upon this while writing a function and am a bit confused.

I am trying to run through a for loop and create multiple lists where the first item is the same. If I use this method, all seems fine.

current_list = [1]

for each in range(5):
    each = current_list + [each]

    print(each)

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

But if I try to make a copy of the list and append to it, I get None

current_list = [1]
for each in range(5):
    each = current_list.copy().append(each)

    print(each)



None
None
None
None
None

Do I need to deep copy the list? What is the best way to copy the contents of the list?

  • `list.append(value)` doesn't return the list, it returns `None` - the appending happens in place. On the other hand the `+` operator creates a new list and returns it. – Primusa Feb 24 '19 at 05:00
  • Is there a better way then to append and then return the entire list? –  Feb 24 '19 at 05:02
  • Ideally you'll just do something like `lst.append(value)` and then just use `lst` later on when you need it since it's in place. If you really want to return you can create a function: `def append(lst, val): lst.append(val); return lst`, but I wouldn't suggest it. – Primusa Feb 24 '19 at 05:11
  • Neither shallow nor deep copying is at all helpful here. – Karl Knechtel Sep 14 '22 at 14:45

0 Answers0