Python Flashcards

1
Q

Iterable vs Iterator

Python

A

An ITERABLE is:
* anything that can be looped over (i.e. you can loop over a string or file) or
* anything that can appear on the right-side of a for-loop: for x in iterable: … or
* anything you can call with iter() that will return an ITERATOR: iter(obj) or an object that defines __iter__ that returns a fresh ITERATOR, or it may have a __getitem__ method suitable for indexed lookup.

An ITERATOR is an object:
* with state that remembers where it is during iteration,
* with a __next__ method that:
* — returns the next value in the iteration
* — updates the state to point at the next value
* — signals when it is done by raising StopIteration
* and that is self-iterable (meaning that it has an __iter__ method that returns self).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

7 // 2

What does above expression evaluate to?

Python

A

3

floor division - divides and rounds down to nearest int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to access idx and element in for loop

Python

A
for idx, element in enumerate(elements):
        print(idx, element)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

for loop using range

Python

A
for x in range(6):
  print(x)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly