Want to learn more? Take the full course at https://learn.datacamp.com/courses/python-data-science-toolbox-part-2 at your own pace. More than a video, you’ll learn hands-on coding & quickly apply skills to your daily work.
Welcome to the course! My name is Hugo Bowne-Anderson and I am a Data Scientist at DataCamp. In this course, the second of the Python Data Science toolbox courses, you’ll learn about iterables, iterators, list comprehensions, and generators — all essential components in the Pythonista’s Data Science toolbox. We will conclude with an entire chapter devoted to a case study in which you’ll apply time and time again techniques learned in both of these courses. Let’s talk about iterators.
There’s no reason to be scared of iterators because you have actually been working with them for some time now! When you use a for loop to print out each element of a list, you’re iterating over the list. You can also use a for loop to iterate over characters in a string such as you see here. You can also use a for loop to iterate an over a sequence of numbers produced by a special range object.
The reason that we can loop over such objects is that they are special objects called iterables: lists, strings, and range objects are all iterables, as are many other Python objects, such as dictionaries and file connections! The actual definition of an iterable is an object that has an associated iter method. Once this iter method is applied to an iterable, an iterator object is created. Under the hood, this is actually what a for loop is doing: it takes an iterable, creates the associated iterator object, and iterates over it!
An iterator is defined as an object that as an associated next() method that produces the consecutive values.
To create an iterator from an iterable, all we need to do is use the function iter() and pass it the iterable. Once we have the iterator defined, we pass it to the function next() and this returns the first value. Calling next() again on the iterator returns the next value until there are no values left to return and then it throws us a StopIteration error.
You can also print all values of an iterator in one fell swoop using the star operator, referred to as the splat operator in some circles. This star operator unpacks all elements of an iterator or an iterable. Be warned, however, once you do so, you cannot do it again as there are no more values to iterate through! We would have to redefine our iterator to do so.
We mentioned before that dictionaries and file connections are iterables as well. To iterate over the key-value pairs of a Python dictionary, we need to unpack them by applying the items() method to the dictionary as you can see here. With respect to file connections, here you can see how to use the iter() and next() methods to return the lines from a file, file dot txt.
This has been your crash course in the fundamentals of iterables and iterators. Use your gained knowledge wisely and have fun iterating!