Python Tutorial: Playing with iterators

Publicado el: 02 marzo 2020
en el canal de: DataCamp
170
4

Want to learn more? Take the full course at https://learn.datacamp.com/courses/py... at your own pace. More than a video, you'll learn hands-on coding & quickly apply skills to your daily work.

---

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!


En esta página del sitio puede ver el video en línea Python Tutorial: Playing with iterators de Duración hora minuto segunda en buena calidad , que subió el usuario DataCamp 02 marzo 2020, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 170 veces y le gustó 4 a los espectadores. Disfruta viendo!