Benefits of Creating List Comprehensions in Python

preview_player
Показать описание
One of Python’s most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code. What are the benefits of replacing a for loop, with a list comprehension? Rather than creating an empty list and adding each element to the end, you simply define the list and its contents at the same time by following this format.

Рекомендации по теме
Комментарии
Автор

Is it also still true that listcomps are faster than a regular for loop?

RbladerOS
Автор

Just the other day I ended up using a List Comprehension in a bit of an unusual way.. While using Pygame for a project, I needed to get a list of the 7 closest neighboring sprites, within a visual range, sorted by distance.. Ended up having to do some lambda trickery, to get that working, or at least I think it works.. heh
neighbors = sorted([
nBody for nBody in allSprites
if < visualRange and nBody != self ],
key=lambda i:
del neighbors[7:]
Compared to a more traditional for-loop, it seemed much faster.. Tho now I'm curious if it actually is the best method, or if a more efficient way to achieve the same results exists.. :/

NikoKun
Автор

Great video! Please, which repl do you use within this video?

valda
Автор

My goto for anything i want to learn using python.

aakashjana
Автор

Personally, I enjoy the challenge of trying to get a convoluted, non-obvious list created all within a single line. Although I do have to admit that at times it would be far easer to follow and debug if it were just written out in loops.

Cynthia_Cantrell
join shbcf.ru