My main issue is with printing the index in the following situations.
catNames = []
while True:
print('Enter the name of cat ' str(len(catNames) 1) ' (or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames [name]
print('The cat names are:')
for name in catNames:
print(str(catNames.index(name) 1) '. ' name)
In this first scenario, the results are
Enter the name of cat 1 (or enter nothing to stop.):
george
Enter the name of cat 2 (or enter nothing to stop.):
sally
Enter the name of cat 3 (or enter nothing to stop.):
chloe
Enter the name of cat 4 (or enter nothing to stop.):
The cat names are:
1. george
2. sally
3. chloe
Which is exactly as expected.
However, when I try this for another scenario, it doesn't work. The next example is as below:
supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
for i in supplies:
print('Index ' str(supplies.index(i) 1) 'in supplies is: ' supplies[i])
I instead get the error stating "TypeError: list indices must be integers or slices, not str".
I understand there's a better way to express the supplies example using range(len(supplies)
but I'm just keen to understand why using the for i in supplies
version doesn't work, although it worked for catNames
. Thanks!
CodePudding user response:
You're doing well here
for name in catNames:
print(str(catNames.index(name) 1) '. ' name)
You're doing different here by using supplies[i]
for i in supplies:
print('Index ' str(supplies.index(i) 1) 'in supplies is: ' supplies[i])
Solution
do the same as when it worked
for i in supplies:
print('Index ' str(supplies.index(i) 1) 'in supplies is: ' i)
Improve
Use enumerate
to yields the current index while iterating, you can even choose the starting value
for idx, supply in enumerate(supply, 1):
print('Index ' idx 'in supplies is: ' supply)
CodePudding user response:
"TypeError: list indices must be integers or slices, not str".
the place where it happens: supplies[i]
supplies
= ['pens', 'staplers', 'flamethrowers', 'binders']
i
= pens
(for example)
so with this line supplies[i]
you try to do thissupplies[pens]
list idx must be like [::-1] or [0] not str, not 'pens'
p.s. the best way to do it is enumerate
:
supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
for idx,i in enumerate(supplies):
print(f'Index {idx} in supplies is: {i}')
# Index 0 in supplies is: pens
# Index 1 in supplies is: staplers
# Index 2 in supplies is: flamethrowers
# Index 3 in supplies is: binders