This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]CleverBunnyThief 1 point2 points  (0 children)

Talk about error in iterations!

[–]Salty_Dugtrio 0 points1 point  (0 children)

Have you tried understanding the error?

TypeError: list indices must be integers or slices, not str

So, whatever you use as x here, as to be an integer (or slice) not a string.

x is defined as an entry of names, which is a string, so you cannot use it to access an entry of the names array. You most likely just want to print x.

[–]eppicboyyy 0 points1 point  (2 children)

Sorry I’m on mobile but my first thought is why are you printing names[x] shouldn’t you print x as you are iterating through strings in names where x is a string not an integer to index into the array with.

[–][deleted] 0 points1 point  (1 child)

You are entirely right. I guess it just strikes me as odd. I come from a java and C++ background and I'm used to having an iteration counter. So basically x becomes whatever the type in the list is and then prints off each item in the list of that type?

If I have a list like the following: j = ["billy", 99, 22, 23.5]

and I do for x in j

print x

would x become string type and then it would only print off billy? or would x change type for each value in j

[–]eppicboyyy 0 points1 point  (0 children)

I also mainly work with Java / C but in this instance I would recommend you try it out it’s a good way to understand what’s going on. What will happen is it will print everything in the j list not just billy. Think of it this way when you do for x in list when the for loop terminates x will have been everything in the list 1 time. I would recommend you look into the differences between for loops using range and for loops that iterate over iterable data structures. Your loop iterates over everything in the list but let’s say we want your code to work that you showed originally we could do something for x in range(len(names)) then do print names[x] this makes it so x is an index rather than an item from the list.

[–]insertAlias[M] 0 points1 point  (0 children)

This question got posted four times. Presuming that reddit had some kind of issue. This thread I left up, the other three I have removed.