How are you supposed to break up a very long list comprehension?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
I have also seen somewhere that people that dislike using '\' to break up lines, but never understood why. What is the reason behind this?
So what's the difference between Generator Expressions and List Comprehensions? The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions are memory efficient than the lists.
The concept of a break or a continue doesn't really make sense in the context of a map or a filter , so you cannot include them in a comprehension.
List comprehensions and generators are not different at all; they are just different ways of writing the same thing. A list comprehension produces a list as output, a generator produces a generator object.
The only difference between Generator Comprehension and List Comprehension is that the former uses parentheses.
[x for x in (1,2,3) ]
works fine, so you can pretty much do as you please. I'd personally prefer
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
The reason why \
isn't appreciated very much is that it appears at the end of a line, where it either doesn't stand out or needs extra padding, which has to be fixed when line lengths change:
x = very_long_term \ + even_longer_term_than_the_previous \ + a_third_term
In such cases, use parens:
x = (very_long_term + even_longer_term_than_the_previous + a_third_term)
You can also make use of multiple indentations in cases where you're dealing with a list of several data structures.
new_list = [ { 'attribute 1': a_very_long_item.attribute1, 'attribute 2': a_very_long_item.attribute2, 'list_attribute': [ { 'dict_key_1': attribute_item.attribute2, 'dict_key_2': attribute_item.attribute2 } for attribute_item in a_very_long_item.list_of_items ] } for a_very_long_item in a_very_long_list if a_very_long_item not in [some_other_long_item for some_other_long_item in some_other_long_list ] ]
Notice how it also filters onto another list using an if statement. Dropping the if statement to its own line is useful as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With