MyMisPal
← Python lessons
Lesson 7 of 13

Lists

PYTHON
courses = ["SQL", "Python", "ERP"]
print(courses[0], courses[-1], len(courses))
courses.append("Networks")
print(courses)

Indexes start at 0 and -1 is the last item. append adds to the end, remove deletes a value, len gives the count.

PYTHON
grades = [88, 92, 75, 64, 99]
print(max(grades), min(grades), sum(grades) / len(grades))
print(sorted(grades))
print(grades[1:3])
PYTHON
for c in ["SQL", "Python", "ERP"]:
    print("-", c)

A list comprehension builds a new list from an existing one, optionally with a condition:

PYTHON
grades = [88, 92, 75, 64, 99]
passed = [g for g in grades if g >= 70]
curved = [g + 5 for g in grades]
print(passed)
print(curved)

Exercises

Exercise 1

You have sales = [1200, 450, 980, 3100, 760]. Print the total, then the highest value, each on its own line.

Exercise 2

From the same list, print a new list with only the sales above 900.

Spotted a mistake on this page, or have an idea to improve the site?