I’m fairly new to programming and I’m really stuck in a problem.
Say I have the following list:
a = [2, "**", 2, "@"]
The list might contain more elements.
What I need to do is change positions between “**” and “@”, so I would have
a = [2, "@", 2, "**"]
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:
for j in range (len(expression)): if expression[j] == "**": if expression[j+2] == "@": expression[j], expression[j+2] = expression[j+2], expression[j] print(expression)
Advertisement
Answer
My comment in an answer (altho pretty simple tbf)
>>> expression = [2, "**", 2, "@", "**"] >>> for j in range (len(expression)): ... if expression[j] == "**": ... if ( ... len(expression) > j +2 ... and expression[j+2] == "@" ... ): ... expression[j], expression[j+2] = expression[j+2], expression[j] ... >>> print(expression) [2, '@', 2, '**', '**']
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)