Data Science with Python

Python Lists and Loops

Python Basics · Lesson 2 of 30

A list holds an ordered collection of values in square brackets. Positions start at 0, and negative positions count from the end.

scores = [72, 88, 95, 61]

print(scores[0])     # first item
print(scores[-1])    # last item
print(scores[1:3])   # a slice: items at positions 1 and 2
print(len(scores))

Changing a list

Lists are mutable, which means you can change them after creating them. append() adds an item to the end.

scores = [72, 88, 95, 61]
scores.append(79)
scores[0] = 75
scores.sort()
print(scores)
print(sum(scores) / len(scores))   # the mean

for loops

A for loop runs a block of code once for each item. The indented lines are the block.

scores = [72, 88, 95, 61]

for s in scores:
    if s >= 70:
        print(s, "pass")
    else:
        print(s, "fail")

range(n) produces the numbers 0 to n-1, which is useful when you need to repeat something a set number of times.

for i in range(5):
    print(i, i * i)

List comprehensions

A list comprehension builds a new list from an existing one in a single line. It is a common way to transform or filter data in Python.

scores = [72, 88, 95, 61]

scaled = [s / 100 for s in scores]
passed = [s for s in scores if s >= 70]

print(scaled)
print(passed)

Try it

Write a comprehension that produces the squares of the numbers 1 to 10. Hint: range(1, 11) gives 1 to 10.