4

When I have a list, say mylist = ['a', 'b', 'c'] and I try to append it to its self

mylist.append(mylist)

I get

['a', 'b', 'c', [...]]

Which is a recursive list, for example, mylist[3][3][1] outputs 'b'

I expected to get

['a', 'b', 'c', ['a', 'b', 'c']]

My first question is how can I get what I expected (if there are many methods I would prefer the most performant). My second question, is what's the reason for this "unexpected" behaviour. Thanks.

I use python3.8.2

loved.by.Jesus
  • 2,266
  • 28
  • 34
  • 2
    Covered in depth [here](https://stackoverflow.com/questions/17160162/what-do-ellipsis-mean-in-a-list) – yatu Apr 23 '20 at 13:18
  • 1
    Use: mylist.append(mylist[:]) – quamrana Apr 23 '20 at 13:19
  • 1
    You are adding the `mylist` object inside `mylist`. any changes in `mylist` will be reflected in both of them if you are mutating them in-place. – Ch3steR Apr 23 '20 at 13:19
  • 2
    You may want to read [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). `append` *always* adds a reference to an object to a list, so you are adding a reference to the list to itself. – chepner Apr 23 '20 at 13:20
  • The way around this is to append a *copy* of the list: `l.append(l[:])`, so that it no longer points to the original list and there's no recursion – yatu Apr 23 '20 at 13:22
  • Hey @yatu It is not right to close the question, the other question you point to is just an explanation to the meaning of [...], but there it is no direct answer to my question. How to append a list to itself. So please, reopen. By the way thanks for giving an answer, though as commentary, please post it as a normal answer :) – loved.by.Jesus Apr 23 '20 at 13:23
  • The explanation is clear from the duplicate. There is recursion because the list being appended points to the same object. You need to append a *copy* of the list – yatu Apr 23 '20 at 13:24
  • I've also added a dupe covering the concept of *copying* – yatu Apr 23 '20 at 13:26
  • Well, I just disagree, the other question is like an encyclopedia answer. If I am no expert, it is an overkill, and somehow I spend a lot of time to find the right answer, which @Orestis Zekai posted in few lines. – loved.by.Jesus Apr 23 '20 at 13:28
  • Ok, yatu, now looks better. Nevertheless, `l.append(l[:])` should be added as an answer for the sake of somebody looking quick for the solution. – loved.by.Jesus Apr 23 '20 at 13:29
  • Well you did ask for *the reason for this "unexpected" behaviour*, which may be a bit complicated to if you're no *expert* as you put it. But it is the actual explanation of what's happening. Once you understand that, it becomes clear that what you need is to append a copy. Give the dupes a good read, it'll help :) – yatu Apr 23 '20 at 13:30

1 Answers1

0

You can use list comprehensions:

mylist.append([x for x in mylist])
Orestis Zekai
  • 897
  • 1
  • 14
  • 29