2. List comprehensions and genera - upalr/Python-camp GitHub Wiki
1. List Comprehensions
1.1 List comprehension Example
Syntex : [[output expression] for iterator variable in iterable]
1.2 List comprehension Syntex Comparison
1.3 Nested Loop Example
1.4 Nested Loop List comprehension
1.5 Build This Using Nested List comprehension
matrix = [[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]
Mind it: [[output expression] for iterator variable in iterable]
# Create a 5 x 5 matrix using a list of lists: matrix
matrix = [[col for col in range(5)] for row in range(5)]
# Print the matrix
for row in matrix:
print(row)
2 Advanced comprehensions
2.1 Conditionals in Comprehensions
2.1.1 Conditionals on The Iterable
2.1.2 Conditionals on The Output Expression
2.2 Dict comprehensions
Another Example:
# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']
# Create dict comprehension: new_fellowship
new_fellowship = {member : len(member) for member in fellowship}
# Print the new list
print(new_fellowship)
3 Intorduction to Generator Expressions
3.1 Generator Expressions
Generator Object: A generator is like a list comprehension except it doesn't store the list in memory. it doesn't construct the list, but it's an object we can iterate over to produce elements of the list (analogous list) as required.
3.1.1 List Comprehensions vs Generators
3.1.2 Printing values from Generators
Here we can see that looping over a generator expression produces the elements of the analogous list. We can also pass a generator to the function list() to create the list.
Moreover, like any other iterator we can pass a generator to the funtion next() in order to iterate through to it's elements. This an example of LAZY EVALUATION. Where by the evaluation of the expression is delayed untill it's value is needed.
INFO: GENERETOR OBJECT IS A ITERATOR BECAUSE WE CAN APPLY NEXT() ON IT
3.1.3 Conditionals in Generators
Anything we can do in a list comprehensions such as filtering and applying conditionals we can also do in a **generator expression **such as you can see here:
3.2 Generator Functions
Generator Functions are functions that when called produce generator objects
Here i have defined a generator function that whenever called with a number n produces a generator object that generates integer 0 through n. We can see within the function defination that i is initialized to 0. Then the first time the generator object is called it yields i = 0, it then add 1 to i and then yield 1 on the next iteration and so on.
Calling generator functions is like calling other functions