Back to Python
2026-03-025 min read

Access Items Using Index (Python Programming)

Learn Access Items Using Index (Python Programming) step by step with clear examples and exercises.

Title: Access Items Using Index (Python Programming)

Why This Matters

In this Python lesson, we will delve into the essential skill of accessing items in a list using their index. This knowledge is vital for manipulating data structures, solving problems, and writing efficient code. Understanding indexing can help you avoid common bugs, perform well in interviews, and tackle real-world programming challenges.

Prerequisites

Before diving into accessing items using index, it's essential to have a solid grasp of the following concepts:

  • Python basics (variables, data types, operators)
  • Lists (creating, modifying, and accessing elements)
  • Conditional statements (if-else)
  • Loops (for loops)

Core Concept

Python lists are ordered collections of items. Each item in a list has an associated index that starts at 0 for the first element. You can access any item in a list by using its index within square brackets ([]).

Here's an example of creating a list and accessing its elements using their indices:

Create a list of numbers

numbers = [1, 2, 3, 4, 5]

Access the first element (index 0)

first_number = numbers[0]

print(f"The first number is {first_number}")

Access the third element (index 2)

third_number = numbers[2]

print(f"The third number is {third_number}")


In the above example, we created a list of five numbers and accessed the first and third elements using their indices. Python uses zero-based indexing, meaning the first element has an index of 0, the second element has an index of 1, and so on.

Worked Example

Let's work through a more complex example to demonstrate how accessing items using index can help solve real-world problems. Suppose we have a list of student grades, and we want to find the average grade for students who scored above 80:

List of student grades

grades = [75, 90, 82, 67, 88, 73, 91, 84]

Initialize variables to store the total and count of scores above 80

total_above_80 = 0

count_above_80 = 0

Iterate through the list and check each grade

for index in range(len(grades)):

grade = grades[index]

if grade > 80:

Add the grade to the total and increment the count

total_above_80 += grade

count_above_80 += 1

Calculate the average grade for students who scored above 80

average_grade = total_above_80 / count_above_80

print(f"The average grade for students scoring above 80 is {average_grade}")


In this example, we used indexing to iterate through the list of student grades and check each one. By accessing each grade using its index within the loop, we were able to find the average grade for students who scored above 80.

Common Mistakes

  1. Forgetting to initialize variables: It's crucial to initialize variables before using them in your code. In our worked example, we initialized total_above_80 and count_above_80 to 0 before iterating through the list.
  2. Using the wrong index: Remember that Python uses zero-based indexing, so you should always check your indices carefully to avoid accessing elements outside the list's range.
  3. Not handling edge cases: Make sure to handle edge cases like empty lists or lists with only one element when writing code that relies on indexing.
  4. ### Edge Case 1: Empty Lists
  • If you try to access an item in an empty list, Python will raise a TypeError. To avoid this, always check if the list is not empty before attempting to access its elements.
  1. ### Edge Case 2: Single-Element Lists
  • If a list contains only one element, accessing it using its index (e.g., my_list[0]) will return that single element. However, if you want to check the length of the list before accessing its elements, use the len() function instead: if len(my_list) > 0.

Practice Questions

  1. Given a list of strings, write a function that returns the third word in each string (assuming words are separated by spaces).
def get_third_word(sentence):
words = sentence.split()
if len(words) >= 3:
return words[2]
else:
return "No third word"
  1. Write a program that reads a list of numbers from the user and finds the sum of all even numbers.
total_even = 0
numbers = []
while True:
number = input("Enter a number (or type 'done' to finish): ")
if number == "done":
break
try:
number = int(number)
numbers.append(number)
except ValueError:
print("Invalid input. Please enter an integer.")

for number in numbers:
if number % 2 == 0:
total_even += number
print(f"The sum of all even numbers is {total_even}")
  1. Given a list of dictionaries representing students with their names, ages, and grades, write a function that sorts the list alphabetically by name and then by grade (in descending order).
def sort_students(student_list):
sorted_students = sorted(student_list, key=lambda student: (student["name"], -student["grade"]))
return sorted_students

FAQ

  1. What happens if I try to access an index that is out of range?
  • If you attempt to access an index that is outside the range of the list, Python will raise an IndexError. To avoid this, make sure to check your indices before using them and handle edge cases like empty lists or lists with only one element.
  1. Can I use negative indices in Python?
  • Yes, you can use negative indices in Python to count from the end of the list. For example, my_list[-1] will return the last element in the list, and my_list[-2] will return the second-to-last element.
  1. Is it possible to change an item's index using its current index?
  • No, you cannot change an item's index using its current index. However, you can use the insert(), remove(), and pop() methods to modify the list's order.
  1. ### Changing Items' Positions with insert()
  • To move an item to a new position in the list using its current index, you can use the insert() method:
my_list = [1, 2, 3, 4]
my_list.insert(2, 0) # Inserts 0 at index 2
print(my_list) # Output: [1, 2, 0, 3, 4]
  1. ### Removing Items with remove() and pop()
  • To remove an item by its value using the remove() method, you can provide the value as an argument:
my_list = [1, 2, 3, 4]
my_list.remove(3) # Removes the first occurrence of 3
print(my_list) # Output: [1, 2, 4]
  • To remove an item by its index using the pop() method, you can provide the index as an argument:
my_list = [1, 2, 3, 4]
removed_item = my_list.pop(1) # Removes and returns the item at index 1 (which is 2)
print(my_list) # Output: [1, 3, 4]
print(removed_item) # Output: 2
Access Items Using Index (Python Programming) | Python | XQA Learn