Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 11 of 25

Lists

A list stores many values in order, inside square brackets. Like strings, lists are indexed from 0.

marks = [72, 85, 90, 64]
print(marks[0], marks[-1], len(marks))

Unlike strings, lists can be changed. append() adds an item to the end, insert() adds at a position, remove() deletes a value, and pop() removes and returns an item.

Built-in functions such as sum(), max(), min() and sorted() work on lists of numbers. A for loop visits every item in turn.

  • nums.append(5) adds 5 at the end
  • nums.sort() sorts the list itself and returns None
  • sorted(nums) gives a new sorted list
  • x in nums checks membership

Key takeaways

  • A list keeps items in order and can be changed. append adds at the end and pop removes and returns the last item.
  • nums.sort() sorts the list itself and returns None, while sorted(nums) returns a new sorted list.
  • Positions start at 0 and -1 is the last item. A slice such as nums[1:4] gives positions 1 to 3.
  • sum(), max(), min() and len() work on lists of numbers.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.