2️⃣

6.2 List Indexing

List Indexing

Each element is stored at a certain index, or position, in the list.

Using my_list, this is what the indexes to elements would look like.

index

  • 0
  • 1
  • 2
  • 3
  • 4

element

  • 1
  • 2
  • "oh no"
  • 4
  • 5.62

You can also get certain elements from a list by indexing it:

my_list = [1, 2, "oh no", 4, 5.62]
print(my_list[1])  # prints 2
print(my_list[3])  # prints 4
# you could also print my_list, which would print all the elements

You can also use a negative index. This retrieves elements, starting the count from the back of the list

my_list = [1, 2, "oh no", 4, 5.62]
print(my_list[-1])  # pints 5.62
print(my_list[-4])  # prints 2

View code on GitHub.

💡

An alternative for negative indexes is the following: my_list[len(my_list)-1]. This example would get the last item. However, it is much more elegant to use negative indexes.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.