History Project
History Project

Reputation: 45

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

song_names = ['Masked Wolf - Astronaut in the Ocean', 'Billie Eilish - bad guy']

async def queue(ctx):
    counter = 1
    print(song_names)
    for str in song_names:
        await ctx.channel.send(counter + song_names[str])
        counter += 1```

This is the error I get:

```  File "E:/.MAIN/Files/Programming/Main/main.py", line 430, in queue
    await ctx.channel.send(counter + song_names[str])
TypeError: list indices must be integers or slices, not str```

Upvotes: 0

Views: 244

Answers (2)

wasif
wasif

Reputation: 15488

You are already iterating over the items sp you can just use the variable and don't use str as variable name:

async def queue(ctx):
    counter = 1
    print(song_names)
    for mystr in song_names:
        await ctx.channel.send(str(counter) + mystr)
        counter += 1

And its looking like you need enumerate():

async def queue(ctx):
    print(song_names)
    for index, mystr in enumerate(song_names):
        await ctx.channel.send(str(index+1) + mystr)

Upvotes: 2

Harshana
Harshana

Reputation: 5476

When looping a list, it normally iterates through each element. In your case, you want to get the index of the current iterating element. For that, You can use enumerate in Python:

Syntax:

enumerate(iterable, start=0)

Full code:

async def queue(ctx):
    counter = 1
    print(song_names)
    for index, song_name in enumerate(song_names):
        await ctx.channel.send(counter + song_names[index])
        counter += 1

Upvotes: 1

Related Questions