GCSE · 18 exercises
Python lists
A list keeps several values in order: [3, 9, 1]. Its items are numbered from 0, like a string's characters.
append() adds to the end; sum(), min(), max(), len() and sorted() work on a whole list. Read numbers from one line with input().split() and int().
numbers = [int(x) for x in input().split()] print(sum(numbers), max(numbers)) numbers.append(0) print(numbers)
Watch for: split() gives text: "10" sorts before "9". Turn each item into a number before comparing or adding.
Exercises
- Sum of a listRead numbers from one line and print their sum.Beginner
- Smallest and largestRead numbers from one line and print the smallest and the largest.Beginner
- Reverse a listRead words on one line and print them in reverse order.Beginner
- Count even numbersRead numbers from one line and count how many are even.Beginner
- Above averagePrint the numbers that are greater than the average of all the numbers, in theirBeginner
- Find a numberFind where a number first appears in a list.Beginner
- Shopping totalRead a shopping list and print the total price with two decimals.Beginner
- Second largestPrint the second largest different number in a list.Beginner
- Remove duplicatesRemove repeated words but keep the first appearance of each, in the original order.Intermediate
- Rotate a listRotate a list k places to the right: the last k items move to the front.Intermediate
- Merge two sorted listsMerge two lists that are each sorted into one sorted list, walking through both atIntermediate
- Running totalPrint the running totals of a list: each position holds the sum of all numbers upIntermediate
- MedianThe median is the middle value of the sorted numbers; with an even count it is theIntermediate
- Most common numberPrint the number that appears most often.Intermediate
- Longest rising runFind the length of the longest stretch of numbers next to each other where each isIntermediate
- Zeros to the endMove every 0 to the end of the list, keeping the other numbers in their order.Intermediate
- Rows of kPrint the items in rows of k; the last row may be shorter.Intermediate
- Sort descendingSort numbers from the largest to the smallest.Intermediate