MAE
MAE

Reputation: 39

Apply a function to every item in a list

I have the following code for pygame but it applies generally to python

expl_sounds = []
for snd in ['expl3.wav', 'expl6.wav']:
    expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd)))

i would like to mute all items in the list individually instead of muting the entire application or mixer. I tried the following:

 for i in expl_sounds:
     expl_sounds[i].set_volume(Sound_Volume)

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

I dont get the error message. The i in the loop is an integer and the mixer.set_Volume is a valid operation for the elements

What would be the correct way to iterate and apply the volume to each element ?

Upvotes: 0

Views: 823

Answers (3)

EvillerBob
EvillerBob

Reputation: 184

The "i" in "for i in expl_sounds" is the sound object itself, not the array index.

Try the following:

for i in expl_sounds:
     i.set_volume(Sound_Volume)

Upvotes: 0

azro
azro

Reputation: 54148

Your error comes from your misunderstanding of the syntax for i in expl_sounds. The i in the loop is an integer isn't true, i is one element of the expl_sounds, a pygame.mixer.Sound instance that you just add before


So use the object directly

for sound in expl_sounds:
    sound.set_volume(Sound_Volume)

To do it by indices, do

for i in range(len(expl_sounds)):
    expl_sounds[i].set_volume(Sound_Volume)

Upvotes: 1

python_ged
python_ged

Reputation: 610

When you write for i in expl_sounds:, you are iterating on the elements in expl_sounds, so you can just do:

for i in expl_sounds:
     i.set_volume(Sound_Volume)

Upvotes: 0

Related Questions