Python Tutorial: Playing with iterators

preview_player
Показать описание

---

We're now going to dive a bit deeper into the world of iterables and iterators by checking out some very cool, very useful functions. The first function, enumerate, will allow us to add a counter to any iterable while the second function, zip, will allow us to stitch together an arbitrary number of iterables.

Let's begin: enumerate is a function that takes any iterable as argument, such as a list, and returns a special enumerate object, which consists of pairs containing the elements of the original iterable, along with their index within the iterable. We can use the function list to turn this enumerate object into a list of tuples and print it to see what it contains.

The enumerate object itself is also an iterable and we can loop over it while unpacking its elements using the clause for index, value in enumerate(avengers). It is the default behaviour of enumerate to begin indexing at 0. However, you can alter this with a second argument, start.

Now let's move on to zip, which accepts an arbitrary number of iterables and returns an iterator of tuples. Here we have two lists, one of the avengers, the other of their names. Zipping them together creates a zip object which is an iterator of tuples. We can turn this zip object into a list and print the list. The first element is a tuple containing the first elements of each list that was zipped. The second element is a tuple containing the second elements of each list that was zipped and so on. Alternatively, we could use a for loop to iterate over the zip object and print the tuples. We could also have used the splat operator to print all the elements!

Now it's your turn to play with these useful functions. Enjoy!
Рекомендации по теме
visit shbcf.ru