Module 1 · Python crash course · Lesson 6 of 66
Loops, range and list comprehensions
Repeat work over items, and build lists in one line.
In this lesson · about 12 minutes
- Loop over a list with for
- Repeat while a condition holds
- Use range() and list comprehensions
A for loop runs its block once for each item, giving the item a name you choose. range(5) gives 0, 1, 2, 3, 4, which is handy for counting. A while loop repeats as long as its condition stays True, so make sure something changes or it never stops.
List comprehensions
Building a new list from an old one is so common that Python has a short form. These two do the same thing:
Exercise
Prices with tax
Use a list comprehension to make with_tax: each price times 1.1, rounded to 2 decimals with round(value, 2).
Exercise
Add up the even numbers
With a for loop over range(1, 21), add up every even number into total.
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.