LearnWave
Learn it. Master it.

Lists

Lists and indexing

Access and change any element of a list.

A list is an ordered, mutable (changeable) sequence of elements, written in square brackets and separated by commas. The elements can be of any type, even mixed: integers, floats, strings, tuples, and other lists.

  • [5, 10, 15, 20, 25, 30]
  • ['onion', 'potato', 'tomato']
  • [101, 23.5, 'Hello', True]

A list inside a list is a nested list: [['Physics', 101], ['Chemistry', 202], ['Maths', 303]].

Elements are reached by index, just like the characters of a string: from 0 to n - 1 counting from the left, or from -1 to -n counting from the right. For nums = [5, 10, 15, 20, 25, 30]:

  • nums[0] is 5, nums[2] is 15, and nums[-1] is 30.
  • len(nums) is 6, so nums[len(nums) - 1] is the last element.
  • An index out of range, such as nums[10], gives an IndexError.
  • The index can be an expression: nums[1 + 2] is nums[3].

Unlike strings, lists are mutable: an element can be replaced in place. veg = ['onion', 'potato', 'tomato']; veg[1] = 'carrot' changes the list to ['onion', 'carrot', 'tomato'].

Lists change; strings don't.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.