Sorting, Searching and List Tricks

Quick maths on a list

marks = [78, 92, 65, 88]
print("Total:", sum(marks))
print("Lowest:", min(marks))
print("Highest:", max(marks))
print("Average:", sum(marks) / len(marks))

Output

Total: 323
Lowest: 65
Highest: 92
Average: 80.75

Sorting

marks = [78, 92, 65, 88]
print(sorted(marks))
print(sorted(marks, reverse=True))
print(marks)

marks.sort()
print(marks)

Output

[65, 78, 88, 92]
[92, 88, 78, 65]
[78, 92, 65, 88]
[65, 78, 88, 92]
  • sorted(list) gives you a new sorted list and leaves the original alone.
  • list.sort() sorts the list itself.

Counting and finding

votes = ["yes", "no", "yes", "yes"]
print(votes.count("yes"))
print(votes.index("no"))

Output

3
1

Joining a list into a string

words = ["Python", "is", "fun"]
print(" ".join(words))
print("-".join(words))

Output

Python is fun
Python-is-fun

List comprehensions: a shortcut

A list comprehension builds a new list in one line. Read it as: “make this, for each item, if this is true”.

numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
print(squares)
print(evens)

Output

[1, 4, 9, 16, 25, 36]
[2, 4, 6]

And a really useful one – reading numbers from a line of input:

numbers = [int(x) for x in input().split()]
print(sum(numbers))

Output (when you type 10 20 30)

10 20 30
60

Tip: A comprehension does the same job as a loop with append(). If it gets hard to read, use the normal loop.

HOME LEARN COMMUNITY DASHBOARD