From the course: Python Data Analysis
Unlock the full course today
Join today to access over 22,500 courses taught by industry experts or purchase this course individually.
Comprehensions
- [Instructor] In Python, especially when you're dealing with data, there are many cases where you want to iterate over a list or a dict performing operation on every element and then collect all the results in a new list, or dict. You can certainly do that with a loop. For instance, picking up the example from the last video, let's compute the first 10 squares, starting with an empty list and adding elements in the body of the loop with append. This works, but we can do better. We can be more pythonic, that is, we can respect Python's specific style and spirit. Python offers a great feature, comprehensions, that let us write shorter, more easily readable code, that achieves the same effect as the loop. In fact, the comprehension is a compressed version of the loop. Let's go through the steps to write one. It's a list we want, so we have brackets. Next, we have the loop. And then we backtrack to the beginning of the…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.