Set Comprehensions

Set comprehensions are similar to list comprehensions, the only difference is the use of braces {} rather than brackets [] and sets can only contain unique values. They are of the form: my_set = { expression for expression in iterable } You can also add an if condition: my_set = { expression for expression in […]

Dictionary Comprehensions

Like the venerable list, dictionaries are extremely useful data structures in Python, and used extensively. Similar to lists, we can build dictionaries from existing collections. The blueprint is: my_dict = { key_expression : value_expression for expression in iterable } This example should make things clearer: Another simple example: Just remember you need to select a […]

List Comprehensions

Whenever you see this pattern to create a list of items: (values) = [] for (value) in (collection): (values).append((expression)) You can replace it with a list comprehension, which takes the form of: (values) = [ (expression) for (value) in (collection)] This: Can be replaced with: Notice how the variable used to iterate over the collection […]