Python Tutorial: Playing with iterators

Learn enumerate and zip, two Python functions for working with iterables. Enumerate returns index-value pairs from any iterable, starting at 0 by default. Zip pairs elements from multiple iterables by position, useful for combining lists like Avengers and their names.
Chapters
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, for example, it's the default behavior of enumerate to begin indexing at 0. However, you can alter this with a second argument. Start as you see here. 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 iterator of tuples 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 element 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.
More from Richie

#359 My Best Friend is AI with Valerie Tiberius, Professor of Philosophy at University of Minnesota

How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon

#358 How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon







