Введение в Python
Теория: Python list comprehensions and generators
Полный доступ к материалам
List comprehensionsand generators in Python
What is a list comprehension
- An expression that creates a collection based on another collection
- Produces a list in general
- Short clear syntax
- Supports predicate clause to filter values
- Might be lazy
- One of the most powerful Python features
Just to compare
List comprehension in depth
[stmt for var in iterable if predicate]
where:
- stmt — any statement,
- var — variable(s) on each iteration step,
- iterable — any iterable value,
- predicate — True/False statement with var in scope
List comprehension — conclusion
- Square brackets syntax
- Creates list
- Computes all values when created
- Aware of long lists (save memory)
- Use it rather than cycles
Set comprehensions
- Same as a list comprehension, but...
- Curly brackets syntax
- Returns a set as a result, so...
- Guaranties unique elements
Dict comprehension
- Curly brackets syntax
- key: value statement
Generator object
- Round brackets syntax
- It's not a tuple!
- Lazy sequence
- Each element computes only when it requires
- Saves memory and CPU
Lazy!
Iteration only
- you cannot access value by index
- you don't know the length
- you can pass through it only one time
- you cannot iterate backwards
- pass it to list/tuple/set to get a common collection
range vs xrange
range(1, 10000)
>>> [1, 2, 3, ..., 9998, 9999, 10000]
xrange(1, 10000)
>>> xrange object
Generators are everywhere
- Mathematical sequence (Fibonacci, progressions)
- Network calls results = (get_data_from_server(user) for user in (...))
- ORM: Django, SQLAlchemy (querysets)
- Parsers (json, xml)
- File readers
- Almost everything in Py3 became lazy
Look for itertools module
Next lesson
- How does iteration work under cover
- Create generators using functions
- Yield operator