1
answer = []
answer.append(i for i in [1,2,3,4,5])
print(answer)

I wrote this code to append every item in the list to the 'answer' variable. However, I got [<generator object <genexpr> at 0x7f56380f4890>].

What am I doing wrong here?

Azhar Khan
  • 3,829
  • 11
  • 26
  • 32
Woanton
  • 11
  • 2
  • `answer = [answer.append(i) for i in [1,2,3,4,5]]` –  Jan 02 '23 at 10:26
  • If you are looking to concatenate two lists, use `extend` like `listA.extend(listB)`. The above comments is also wrong, as it will create a list of `None` values. – Kris Jan 04 '23 at 05:08
  • @SulemanElahi don't use list comprehensions for side-effects. A list comprehension is meant for when you want to build a loop. Your line of code will fail, because `answer.append` returns `None`, so after doing all that work, the list comprehension creates a useless list of `None`s. Now, normally that would just be wasted work because you'd throw that list away immediately, but in your case you then go on to assign that list of `None`s to `answer`, leaving you with a list of `None`s for all that hard work you just made the computer do! – Pranav Hosangadi Jan 04 '23 at 05:34
  • OP, congratulations! You have unlocked _[¡¡generators!!](https://stackoverflow.com/questions/1756096/understanding-generators-in-python)_ – Pranav Hosangadi Jan 04 '23 at 05:36
  • Does this answer your question? [What is the difference between Python's list methods append and extend?](https://stackoverflow.com/questions/252703/what-is-the-difference-between-pythons-list-methods-append-and-extend) – Pranav Hosangadi Jan 04 '23 at 05:40

1 Answers1

2

To print the list of elements that are appended to answer, you can use a loop to iterate through the list comprehension and append each element to answer:

answer = []
for i in [1, 2, 3, 4, 5]:
    answer.append(i)
print(answer)

Alternatively, you can use the extend method to add all the elements from the list comprehension to answer at once:

answer = []
answer.extend(i for i in [1, 2, 3, 4, 5])
print(answer)
Murari Kumar
  • 122
  • 2
  • 12
  • 4
    No need of iterating again in extend. It can be just `answer.extend([1, 2, 3, 4, 5])` – Kris Jan 04 '23 at 05:09