Help! Getting `TypeError: 'int' object is not subscriptable` when trying to access Python list `data structures`.
Hey everyone, i'm super new to Python and just trying to wrap my head around the basics, especially how to work with lists. I'm following some tutorials and trying to make sense of iteration.
i'm trying to write a simple script that iterates through a list of numbers and prints each number using its index. i thought i had it right, but i keep hitting a wall.
I wrote this little snippet:
my_numbers = [10, 20, 30, 40, 50]
for number in my_numbers:
print(my_numbers[number])
When I run this, instead of printing out 10, 20, 30, etc., I get a frustrating error. It seems like Python is confused about what 'number' is inside the loop.
This is what my console spits out:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: 'int' object is not subscriptable
I thought that for number in my_numbers: would make number be the index (0, 1, 2...) for each item. So then my_numbers[number] should work, right? I'm clearly misunderstanding something fundamental about how Python iterates or handles list data structures. Is it treating 'number' as the *value* itself, not the index?
My Questions:
- Can someone explain why I'm getting this
TypeError: 'int' object is not subscriptable? - What's the correct, Pythonic way to iterate through a list and access its elements, especially if I need the index for something else later?
- Any general tips for a complete beginner trying to grasp Python's core
data structureslike lists?
Thanks in advance for any help or pointers, i really appreciate it!
1 Answers
MD Alamgir Hossain Nahid
Answered 5 hours agoI thought thatI completely understand this confusion; it's a very common point of misunderstanding for beginners diving into Python, and honestly, I've seen similar logical traps in debugging complex campaign scripts. Let's break down why you're encountering the `TypeError` and how to handle Python list iteration effectively.for number in my_numbers:would makenumberbe the index (0, 1, 2...) for each item. So thenmy_numbers[number]should work, right?
Understanding the `TypeError: 'int' object is not subscriptable`
The core of the issue lies in how Python's `for...in` loop works with sequences like lists. When you write:for number in my_numbers:
Python does not assign the *index* of each element to the `number` variable. Instead, it directly assigns the *value* of each element.
Let's trace your code snippet:
my_numbers = [10, 20, 30, 40, 50]
for number in my_numbers:
print(my_numbers[number])
1. **First iteration**: `number` becomes `10` (the first value in `my_numbers`).
2. **Inside the loop**: You then try to execute `print(my_numbers[number])`, which translates to `print(my_numbers[10])`.
3. **The problem**: `10` is an integer. You are attempting to use an integer (the value `10`) as an index to access an element within `my_numbers`. However, `my_numbers` only has indices `0` through `4`. More critically, Python sees that `number` (which is `10`) is an `int` object, and `int` objects themselves cannot be "subscripted" (i.e., you cannot do `10[something]` โ an integer is not a sequence that holds other elements accessible by `[]`). This is why you get `TypeError: 'int' object is not subscriptable`. Python is telling you that `10` is just a number; you can't try to look inside it as if it were a list or string.
Correct Pythonic Ways to Iterate Through a List
There are several correct and Pythonic ways to iterate through a list, depending on whether you need the index, the value, or both. Understanding these **Python iteration techniques** is fundamental for efficient **web development** and scripting.1. Iterating by Value (Most Common and Pythonic if you only need the value)
If you only need to access the *elements themselves* and not their indices, this is the simplest and most Pythonic approach:my_numbers = [10, 20, 30, 40, 50]
for number_value in my_numbers:
print(number_value)
**Output:**
10
20
30
40
50
Here, `number_value` directly takes on the values `10`, `20`, `30`, etc.
2. Iterating with `enumerate()` (When you need both Index and Value)
This is the recommended Pythonic way when you need both the index and the value of each item. The `enumerate()` function adds a counter to an iterable and returns it as an enumerate object.my_numbers = [10, 20, 30, 40, 50]
for index, number_value in enumerate(my_numbers):
print(f"Index: {index}, Value: {number_value}")
**Output:**
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50
This is clean, readable, and highly efficient.
3. Iterating by Index using `range(len())` (When you need to modify the list in place or for specific logic)
While less Pythonic for simply reading values, this method is useful if you need to modify the list elements *in place* or if your logic specifically requires working with indices.my_numbers = [10, 20, 30, 40, 50]
for index in range(len(my_numbers)):
print(f"Index: {index}, Value: {my_numbers[index]}")
# Example: Modify the list element at the current index
my_numbers[index] = my_numbers[index] * 2
print("Modified list:", my_numbers)
**Output:**
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50
Modified list: [20, 40, 60, 80, 100]
In this case, `index` correctly takes on the integer indices `0`, `1`, `2`, `3`, `4`, allowing `my_numbers[index]` to work as you initially intended.