Module 3: Functional programming III Flashcards
- [ ] Iterables, Iterators and Generators, Lazy Computation, Real-World Examples of Functional Programming
What is an iterable?
- Iterables act as containers of other objects i.e. collection of items
- Iterations can be used to access the contained objects individually
Give me examples of iterables.
- Lists
- Tuples
- Dictionaries
- Strings
What are ways to create iterables?
- for…in… expressions
- List comprehension
- Set comprehension
- Dictionary comprehension
What does this code showcase?
myList = [‘blue’, ‘red’, ‘yellow’]
for color in myList:
print(color)
for …in… expression
What is a list comprehension?
It is a useful and compact way to create a list based on an operation or condition applied to another iterable
What does this code show?
colors=[‘red’, ‘blue’, ‘yellow’]
li=[” “+s+” “ for s in colors]
for s in li:
print(s)
List comprehension
colors=[‘red’, ‘blue’, ‘yellow’]
#List comprehension:
li=[” “+s+” “ for s in colors]
#Access elements:
for s in li:
print(s)
(set and dict comprehensions look basically the same)
What is an iterator?
- Objects that store a state (normally an index)
NOT collections - An iterator is an object that contains a __next__ method
What is the relation between an iterable and an iterator?
When looping over an iterable, the iterator of that iterable will tell us which item of the collection is the next to be read.
What happens when we iterate over iterable objects?
We are implicitly calling the iter() built-in function with the iterable object as an argument
- iter(x) checks if object x has an iter method
- iter returns an iterator for the iterable
What does iter() return
iter() returns an iterable object
What does the __next__ method return?
Returns the next item stored in a collection. When there are more items left, this method will raise a StopIteration exception, which will be caught by iterating expression.
What does the order of access depend on when using iterators?
The order of access (i.e. which object is the next) depends on the type of collection
What are types of collections?
- Ordered types
- Unordered types
Explain ordered types and give examples.
The order of access is the same as the insertion order.
e.g. lists, strings, tuples, and dicts
Explained unordered types and give example.
The order of access is unknown to the programmer
e.g. sets
mySet=set((5,4,3,2,1))
for s in mySet:
print(s, end=”,”)
Do we know in which order these items will be printed? Why or why not.
We don’t know the print order as a set is a unordered type, meaning the order of access is unknown to the programmer.