Skip to content
Advertisement

How to transform the first element for all tuples move one place afterwards in Python?

For example, if I had a list of tuples like: [('first', 0),('second', 1),('third', 2)] I want to transform it to: [('default', 0),('first', 1),('second', 2)]

the second column stays the same but the first column which is the first element move one place afterward for all tuples and the first place will be replaced 'default'. Is there any quick method to do this?

Advertisement

Answer

One line solution

#l = [('first', 0),('second', 1),('third', 2)]
[('default' if i == 0 else l[i-1][0], y) for i, (_, y) in enumerate(l)]
#[('default', '0'), ('first', '1'), ('second', '2')]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement