Python Tutorial: Playing with iterators

Veröffentlicht am: 02 März 2020
auf dem Kanal: 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!


Auf dieser Seite können Sie das Online-Video Python Tutorial: Playing with iterators mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer DataCamp 02 März 2020 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 170 Mal angesehen und es wurde von 4 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!