
"All forms of iteration do the same thing in Python. All of these Python features rely on the same iterator protocol (which you do not need to know to use it): All 4 of those Python features rely on the same underlying mechanism: iterating over an iterable object. Let's prove this to ourselves by doing some weird things with dictionaries and strings. Looping over dictionaries gives keys When you loop over a dictionary, you'll get the keys in that dictionary: If you loop over a dictionary in a list comprehensions, you'll also get keys: Python's * operator also relies on iteration... so if we use * to unpack a dictionary into separate positional arguments in a function call, we'll also get keys: The same thing happens if we use * to unpack a dictionary into a list: Tuple unpacking also relies on iteration. Anything you can loop over can be unpacked. Since we know there are 3 items in our dictionary, we could unpack it: And of course, as strange as it may seem, we get our dictionary's keys when we unpack it:"
"What would happen if we turned our dictionary into a list, by passing it to the list constructor? Well... list() will loop over whatever iterable is given to it and make a new list out of it. And when we loop over a dictionary... we get keys! So passing a dictionary to the built-in list constructor will return a list of that dictionary's keys. All forms of iteration are the same in Python. Iterating over a dictionary will give you keys, no matter what tool/feature is doing the iteration! Aside: course if you want key-value pairs you can get them using the dictionary items method. Looping over strings provides characters Strings are also iterables. What do we get when we loop over strings? Characters! The string join method accepts an iterable of strings and joins them together. So we could pass a list of strings to the join method: But... what would happen if we passed a single string to the join method? Well... join will try to itera"
All iteration features in Python rely on the same iterator protocol and operate by iterating over an iterable object. Looping over a dictionary yields its keys whether using a for-loop, a list comprehension, the splat (*) operator for function calls or list construction, tuple unpacking, or converting to a list. Tuple unpacking and star-unpacking depend on the same iteration mechanism so unpacking a dictionary returns keys. The list() constructor iterates its argument and therefore produces a list of dictionary keys when given a dict. Strings are iterables that yield individual characters when iterated, and str.join iterates over a string argument to obtain those characters.
Read at Pythonmorsels
Unable to calculate read time
Collection
[
|
...
]