Skip to content
Advertisement

How to change list elements positions in a for loop in Python

I’m fairly new to programming and I’m really stuck in a problem.

Say I have the following list:

JavaScript

The list might contain more elements.

What I need to do is change positions between “**” and “@”, so I would have

JavaScript

I’ve been trying to do it with a for loop, using element indexes to perform the change, but the list index is getting out of range.

How could I do it?

Here’s my code:

JavaScript

Advertisement

Answer

My comment in an answer (altho pretty simple tbf)

JavaScript

Explanation: if the current value is ** you are attempting to access j+2. However, your list might not have that index (for example what if ** is the last element?). To cater for this case I extend your if statement to first check for length and then check for j+2 values. If/when the first check/condition fails, the second condition is skipped (not checked) and thus the IndexError does not happen.

(updated the input list to show that even ** at the end of the list wont raise an error)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement