List comprehension

Hello, can you guys recommend anything for a more comprehensive lesson on list comprehension? I understand the basics of it but anything more than a = [i-5 for i in b <30] and so on and I’m completely lost. In the loops project I had to use range(), len() and other stuff in list comprehension and it just went completely over my head.

I wouldn’t worry about it overmuch, it’s possible to write extremely complex nested list comprehensions with ternary conditional expressions and multiple function calls but that’s probably a bad idea, keep it simple and readable. If it gets much more complicated you’d probably want a function or something along those lines instead.

If you really want to perfect the syntax try a web search for some examples, plenty of blogs or educational sites all have their own descriptions and examples; one of them should hopefully match your own way of thinking.

My only suggestion would be to consider splitting it onto multiple lines if you like and the syntax often becomes a lot more readable. For example the following separates each part into a something that’s almost identical to the equivalent for loop.

lst = [
    number  # expression
    for number in number  # target name and for clause
    if number not in bad_numbers  # optional if clause
]
# basically equivalent to the following-
lst = []
for number in numbers:
    if number not in bad_numbers:
        lst.append(number)
2 Likes