

Enumerate python code#
This allows us to zip differently sized collections without losing data, but it requires some techniques we haven't looked into yet, such as importing code from other files. In addition to all of these, we have a post talking about another function called zip_longest. We also have a blog post on enumerate, which you can find here, and one on zip, which you can read here. If you want to learn more about unpacking, we have a blog post which goes into more detail. This time we're writing a short program to validate credit cards! Additional resources Once you're done with the exercises, we have another project for you today. You can find our solutions to the exercises here. For example, try to zip a list containing three items, and a tuples containing four items.

The data represents a student's name, their student id number, and their major and minor disciplines in that order.ģ) Investigate what happens when you try to zip two iterables of different lengths. ( "John Smith", 11743, ( "Computer Science", "Mathematics" )) This is actually a really useful feature, but it's also a common source of bugs if you're not familiar with this behaviour.Īn easy way to bypass this limitation is to just convert the iterator to a non-iterator collection, like a list or tuple. We're not going to be talking about iterators in any depth in this series, as iterators are an advanced topic, but one key feature of iterators is that they're consumed when we request their values. The reason that this happens is because zip and enumerate produce something called an iterator. The returned object is an enumerate object. If you try to iterate over movies after the initial loop, you'll also find that it contains no values. The enumerate() function adds counter to an iterable and returns it. Movies = for title, director, year in movies : print ( f ".
