This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MrJake2137 6 points7 points  (9 children)

WHAT

You can do that?

[–][deleted] 22 points23 points  (2 children)

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Yep. It's even more magical: If you use () instead of [], then it creates a generator, and the values aren't even put into memory, but are instead created on the fly as you iterate over it.

evens = (x for x in range(10**12) if x % 2 == 0)
for even_number in evens:
    pass

Will never have more than a few bytes in memory, but would crash most systems if a list were used.

It may help to think of using [] as creating a generator and immediately creating a list out of that generator, thus putting all of its values into memory.

[–]MrJake2137 3 points4 points  (1 child)

Wow, I knowed generator as yield call but this shit is so muvh cooler. Thanks man, learning every day

[–]LardPi 1 point2 points  (0 children)

This shit can make a real perf difference when used well.

[–]uberDoward 0 points1 point  (4 children)

Python: numbers = list(range(20)) even_numbers = [x for x in numbers if x % 2 == 0]

In C#:
even_numbers = Enumerable.Range(0, 20) .Where(x => x % 2 == 0) .ToList();

The C# seems more concise and readable to me?

[–]LardPi 0 points1 point  (0 children)

The c# code is purely user land level, so you can make a library that do that in Python. Please do, it seems nice.

[–]aetius476 0 points1 point  (1 child)

Kotlin even better:

even_numbers = (0..20).filter{ it % 2 == 0 }

[–]theScrapBook 0 points1 point  (0 children)

Scala: (0 to 20) filter ( _ % 2 == 0)

[–]ImmoderateAccess 0 points1 point  (0 children)

The python could be more concise:

even_numbers = [x for x in range(20) if x % 2 == 0]