dmnte
dmnte

Reputation: 155

similar list.append statements returning different results

I have the two expressions below, which to me are basically the same but the first line gives a list with generator inside rather than the values while the second one works fine.

I just wanted to know why this happens what is a generator and how its used.

newer_list.append([sum(i)] for i in new_list)

for i in new_list:
        newer_list.append([sum(i)])

Upvotes: 0

Views: 39

Answers (2)

Kewl
Kewl

Reputation: 3417

A generator is a way for Python to keep from storing everything in memory. The expression ([sum(i)] for i in new_list) is a formula for generating the items in a list. To keep from storing that list in memory, it just stores the function it would need to execute, which has less of a memory footprint.

To turn a generator into a list, you can just do list([sum(i)] for i in new_list), or in this case ([[sum(i)] for i in new_list])

Upvotes: 1

internet_user
internet_user

Reputation: 3279

The first one has a generator expression (sum[i] for i in new_list), while the second one just loops, adding the sum.

It is possible you wanted something like newer_list.extend([sum(i) for i in new_list]), where extend concatenates lists instead of just appending, and the whole thing is wrapped in brackets so it's a list comprehension instead of a generator.

Upvotes: 2

Related Questions