Python 3.2: Can I multiply a tuple in a list without concatenating the individual tuples into one tuple?

StackOverflow https://stackoverflow.com/questions/15410826

  •  23-03-2022
  •  | 
  •  

Question

I like the simplicity of this list comprehension syntax,

waves = [(frequency, amplitude) * wave_count]

but in this case I don't like that it concatenates the multiplied tuple into one long tuple.

Is there a simple way to effectively multiply a tuple to become separate tuples in a list?

Thanks,

Victor

P.S.

Oh, wait! I just figured it out, but I think I'll post this question anyway since it confused me.

This did it:

waves = [(frequency, amplitude)] * wave_count
Was it helpful?

Solution

Use a real list comprehension:

waves = [(frequency, amplitude) for _ in range(wave_count)]

or just multiply the list as you did:

waves = [(frequency, amplitude)] * wave_count

The latter is safe in this case because tuples are not mutable.

The first option creates a new tuple for each iteration of the loop, the second option expands the list using wave_count references to the same tuple. If you used a mutable instead (say, a list or dict), then that could lead to unexpected results, but it does use less memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top