notsara
notsara

Reputation: 25

Change the position of the value in my list

Im trying to find a way to change the order of my list at the end.

For example, for a list of 4 boxes, we invert the values ​​of boxes 1 and 2 and we reverse the values ​​of boxes 3 and 4.

normal_list([1, 2, 3, 4]) I want the first number to be even and the second to be odd like this : [2, 1, 4, 3]

creating an empty list lst = [] # number of elemetns as input

n = int(input("Enter an even number: "))  
if (n % 2) == 0:  
   print("Enter the desired",n,  "numbers : ".format(n))  
else:  
   print("Please enter an even number")
   

# iterating till the range
for i in range(0, n):
  if n % 2 == 0:
            ele = int(input())
            lst.append(ele) # adding the element
           
  else :
    break

print('this is the list : ',lst)

def Split(mix): 
    ev_li = [] 
    od_li = [] 
    for i in mix: 
        if (i % 2 == 0): 
            ev_li.append(i) 
        else: 
            od_li.append(i) 
    print("This is the new list:", ev_li + od_li) 

  
mix = lst 
Split(mix)

Upvotes: 0

Views: 1262

Answers (3)

RufusVS
RufusVS

Reputation: 4127

@Mark Meyer has given a terrific answer, but here are a couple of the alternatives he spoke of:

A very explicit swapper:

l = [1, 2, 3, 4]

for p in range(0,len(l),2):
    l[p],l[p+1]=l[p+1],l[p]

print (l)

And the truly awful:

l = [1, 2, 3, 4]

l = [l[p^1] for p in range(len(l))]

print (l)

I leave it to the reader to figure out that last one.

Upvotes: 2

Raspberry1111
Raspberry1111

Reputation: 78

You can loop through an even list and an odd list at once using zip() to do this.


old_list = [1,2,3,4,5,6]

# Make empty list of same length
new_list =  []
even = []
odd = []
for item in old_list:
    
    # Check if even
    if item % 2 == 0:
        even.append(item)
    else:
        odd.append(item)
# Loop through both lists at once
for e, o in zip(even, odd):
    # add the even item first
    new_list.append(e)
    # then add the odd
    new_list.append(o)
    
print(new_list) # Returns: [2,1,4,3,6,5]

Upvotes: 0

Mark
Mark

Reputation: 92440

There are many ways to do this. You can loop over pairs of indexes by zipping a range() iterator. This will allow you to swap the values in place:

l = [1, 2, 3, 4]

e = iter(range(len(l)))

for a, b in zip(e, e): # pairs of indexes like (0, 1), (2, 3)...
    l[a], l[b] = l[b], l[a]
    
print(l)
# [2, 1, 4, 3]

Alternatively, you could make a new list with a list comprehension by zipping the list with itself into pairs and then reversing the pairs:

l = [1, 2, 3, 4]

new_l = [n for pair in zip(l[::2], l[1::2]) for n in reversed(pair)]
print(new_l)
# [2, 1, 4, 3]

The behavior is not really specified when the list is not an even length.

Upvotes: 3

Related Questions