This code does not work for me where I have to exchange elements of a list in pairs:
def exchange(l):
if len(l) <= 1:
return l
else:
result = []
i = 0
while i < len(l) - 1:
result += [l[i+1]] + [l[i]]
i += 2
if len(l) % 2 == 1:
result += [l[len(l)-1]]
return result
Apparently what your code has to do is exchange the elements of even index with those of odd index, that is,
l[0]
it is exchanged withl[1]
,l2[2]
withl[3]
, etc. When the number of elements is odd, the last one "is left over" in a certain way, and it is not exchanged with anyone.Your code almost did it, except that you didn't handle the "odd number of elements" case well, because in that case the last element must be added last, and not in each iteration as you were doing.
This is your code modified so that the last element is added to the end. It was enough to move a few lines out of the loop:
Now your code doesn't actually modify the parameter
l
. That is, if you call it with:exchange(datos)
, the variabledatos
is not modified, but a new list is built and returned as a result. You'll have to dodatos = exchange(datos)
to see the changes reflected in that variable.Another alternative would be for the list passed as a parameter to be modified in place , instead of creating a new one. The following code (which is shorter) does that:
I use here some tricks:
range(a,b,c)
returns a series of integers that start ata
, end before reaching or overflowingb
, and are spaced fromc
inc
units. In my case I use it to generate the indicesi
that start at zero, advance 2 by 2, and end before the last valid even index.//2
) and multiplying the result by 2. So, if the number of elements in the list was even (for example 10), that expression would return 10. But if it was odd (for example 9) it would return 8. That saves me from having to look and treat specially if the number of elements was even or odd. If it is odd, the loop will stop before reaching the last one, which will therefore not be played.a, b = b, a
that allows you to exchange two variables without the need for an intermediate one. In this case the elements to be exchanged are two from the listl
.If you invoke this for example like this:
The variable
l
will be modified. The function does not return anything, but rather modifies the list received as a parameter. After execution the new value ofl
is:Lists have the function
sort
to sort them.