Python Comprehensions
List Comprehensions are a special kind of syntax that let us create lists out of other lists, and are incredibly useful when dealing with numbers and with one or two levels of nested for loops.
Read
List comprehension
This is how we create a new list from an existing collection with a For Loop:
>>> names = ['Charles', 'Susan', 'Patrick', 'George']
>>> new_list = []
>>> for n in names:
... new_list.append(n)
...
>>> new_list
# ['Charles', 'Susan', 'Patrick', 'George']
And this is how we do the same with a List Comprehension:
>>> names = ['Charles', 'Susan', 'Patrick', 'George']
>>> new_list = [n for n in names]
>>> new_list
# ['Charles', 'Susan', 'Patrick', 'George']
We can do the same with numbers:
>>> n = [(a, b) for a in range(1, 3) for b in range(1, 3)]
>>> n
# [(1, 1), (1, 2), (2, 1), (2, 2)]
Adding conditionals
If we want new_list
to have only the names that start with C, with a for loop, we would do it like this:
>>> names = ['Charles', 'Susan', 'Patrick', 'George', 'Carol']
>>> new_list = []
>>> for n in names:
... if n.startswith('C'):
... new_list.append(n)
...
>>> print(new_list)
# ['Charles', 'Carol']
In a List Comprehension, we add the if
statement at the end:
>>> new_list = [n for n in names if n.startswith('C')]
>>> print(new_list)
# ['Charles', 'Carol']
To use an if-else
statement in a List Comprehension:
>>> nums = [1, 2, 3, 4, 5, 6]
>>> new_list = [num*2 if num % 2 == 0 else num for num in nums]
>>> print(new_list)
# [1, 4, 3, 8, 5, 12]
Set comprehension
>>> b = {"abc", "def"}
>>> {s.upper() for s in b}
{"ABC", "DEF"}
Dict comprehension
>>> c = {'name': 'Pooka', 'age': 5}
>>> {v: k for k, v in c.items()}
{'Pooka': 'name', 5: 'age'}
A List comprehension can be generated from a dictionary:
>>> c = {'name': 'Pooka', 'age': 5}
>>> ["{}:{}".format(k.upper(), v) for k, v in c.items()]
['NAME:Pooka', 'AGE:5']
- Previous
- Next
Python abs() built-in function
Python aiter() built-in function
Python all() built-in function
Python any() built-in function
Python ascii() built-in function
Python bin() built-in function
Python bool() built-in function
Python breakpoint() built-in function
Python bytearray() built-in function
Python bytes() built-in function
Python callable() built-in function
Python chr() built-in function
Python classmethod() built-in function
Python compile() built-in function
Python complex() built-in function
Python delattr() built-in function
Python dict() built-in function
Python dir() built-in function
Python divmod() built-in function
Python enumerate() built-in function
Python eval() built-in function
Python exec() built-in function
Python filter() built-in function
Python float() built-in function
Python format() built-in function
Python frozenset() built-in function
Python getattr() built-in function
Python globals() built-in function
Python hasattr() built-in function
Python hash() built-in function
Python help() built-in function
Python hex() built-in function
Python id() built-in function
Python __import__() built-in function
Python input() built-in function
Python int() built-in function
Python isinstance() built-in function
Python issubclass() built-in function
Python iter() built-in function
Python len() built-in function
Python list() built-in function
Python locals() built-in function
Python map() built-in function
Python max() built-in function
Python memoryview() built-in function
Python min() built-in function
Python next() built-in function
Python object() built-in function
Python oct() built-in function
Python open() built-in function
Python ord() built-in function
Python pow() built-in function
Python print() built-in function
Python property() built-in function
Python range() built-in function
Python repr() built-in function
Python reversed() built-in function
Python round() built-in function
Python set() built-in function
Python setattr() built-in function
Python slice() built-in function
Python sorted() built-in function
Python staticmethod() built-in function
Python str() built-in function
Python sum() built-in function
Python super() built-in function
Python tuple() built-in function
Python type() built-in function
Python vars() built-in function
Python zip() built-in function
Python Args and Kwargs
Python Basics
Python built-in functions
Python Comprehensions
Python Context Manager
Python Control Flow
Python Dataclasses
Python Debugging
Python Dictionaries
Python Exception Handling
File and directory Paths
Python Functions
Python Json and YAML
Python Lists and Tuples
Python Main function
Manipulating strings
Python OOP Basics
Reading and writing files
Python Regular Expressions
Python Sets
Python Setup.py
Python String Formatting
Python Virtual environments