List comprehension without [ ] in Python

The other respondents were correct in answering that you had discovered a generator expression (which has a notation similar to list comprehensions but without the surrounding square brackets). In general, genexps (as they are affectionately known) are more memory efficient and faster than list comprehensions. HOWEVER, it the case of ”.join(), a list comprehension is … Read more

Accessing class variables from a list comprehension in the class definition

Class scope and list, set or dictionary comprehensions, as well as generator expressions do not mix. The why; or, the official word on this In Python 3, list comprehensions were given a proper scope (local namespace) of their own, to prevent their local variables bleeding over into the surrounding scope (see List comprehension rebinds names … Read more

Flattening a shallow list in Python [duplicate]

If you’re just looking to iterate over a flattened version of the data structure and don’t need an indexable sequence, consider itertools.chain and company. >>> list_of_menuitems = [[‘image00’, ‘image01’], [‘image10’], []] >>> import itertools >>> chain = itertools.chain(*list_of_menuitems) >>> print(list(chain)) [‘image00’, ‘image01’, ‘image10′] It will work on anything that’s iterable, which should include Django’s iterable … Read more