Reputation: 11
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?
Upvotes: 1
Views: 45
Reputation: 122
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)
Upvotes: 2