Python中如何为数组添加索引?TypeError报错原因及可迭代对象解析
Hey there! Let's work through your problem together—first we'll figure out why that TypeError is popping up, then I'll explain what iterables are, and finally fix up your code to do what you want.
Why You're Seeing That TypeError
Let's look at the problematic part of your code first:
hh=[] p=int(len(hh)) # ... for cc in p :
First off, you're resetting hh to an empty list every time the loop runs—so len(hh) is always 0, making p the integer 0. When you try to do for cc in p, Python tries to loop over the contents of p... but integers are single values, not collections you can iterate through. That's exactly why you get TypeError: 'int' object is not iterable.
On top of that, your code has a few other logic snags:
hh.append(i,num)is invalid syntax—append()only takes one argument. If you want to store an index and value together, you need to pass a tuple like(index, value).- You're reusing the variable
ccfor both a counter and a loop variable, which is causing confusion.
What's an Iterable Object, Anyway?
Put simply, an iterable is any object that Python can loop through by pulling out one element at a time. Think of it like a container with multiple items inside. Common examples in Python include:
- Lists, tuples, strings, sets, and dictionaries
- Generators and iterators (fancier, but still iterable)
When you write for item in something, that "something" has to be iterable. Single-value types like integers or floats don't have multiple elements to pull out, so they're not iterable.
Fixed Code to Build an Indexed Array
It looks like you want to add values to an array, view the indexed array when you type "lunch", and quit with "end". Here's a corrected version that does exactly that:
# Initialize the list OUTSIDE the loop so we don't reset it every time indexed_array = [] while True: user_input = input("Enter a value for the array, type \"lunch\" to view the indexed array, or \"end\" to quit: ") if user_input == "lunch": # Print the array with indices (using enumerate is perfect for this!) print("\nHere's your indexed array:") for idx, value in enumerate(indexed_array): print(f"Index {idx}: {value}") # If you want to store indices directly in the list, uncomment below: # print(indexed_array) elif user_input == "end": print("Exiting program!") break else: # The next index is just the length of the list (since indices start at 0) new_index = len(indexed_array) # Add the index and value as a tuple to the list indexed_array.append((new_index, user_input)) print(f"Added '{user_input}' at index {new_index}\n")
Quick Notes on the Fix:
- Moving
indexed_array = []outside the loop means we keep all the values you input instead of wiping them each time. enumerate()is a handy built-in function that automatically gives you both the index and value of each element in a list—no need to track counters manually.- If you prefer to store the index directly with the value in the list, we use a tuple
(new_index, user_input)sinceappend()only takes one argument.
内容的提问来源于stack exchange,提问作者Milad Motmaen

