From the course: Python Data Analysis
Unlock the full course today
Join today to access over 24,500 courses taught by industry experts.
Comprehensions - Python Tutorial
From the course: Python Data Analysis
Comprehensions
- [Instructor] When working with data in Python, there are many cases when we want to iterate over a list or dict, perform an operation on every element, and then collect all the results into a new list or dict. We can certainly do that with a for loop. For instance, we can compute the first 10 squares, starting with an empty list, and adding elements to the list in the body of the loop. But we can do better. We can be more Pythonic. Python offers a great feature comprehensions that lets us write shorter, more easily readable code. In essence, the comprehension will be a compressed version of the for loop. Let's go through the steps. We want a list, so we have brackets. In front, we have the body of the loop, the square. In the back, we write the looping construct for variable in iterable. Here, it's a range. The result is the same as writing out the loop, but we managed to express the same meaning in a very readable and very efficient way. We can also filter the list of elements that…