Home > Software design >  Flip half of a list and append it to itself
Flip half of a list and append it to itself

Time:12-07

Im trying to flip half of the elements inside of a list and then spend it onto itself, for example, if I pass the list [1, 8, 7, 2, 9, 18, 12, 0] into it, I should get [1, 0, 7, 18, 9, 2, 12, 8] out, here is my current code

def flip_half(list):
    for i in range(0,len(list)):
        if i % 2 != 0:
            listflip = list[i] 
            print(listflip)
    
            
    return list

CodePudding user response:

You can directly assign slices in python. So if you can determine the slice you want to assign from and to, you can directly change the elements. This assign from every other element in reverse l[::-2] to every other element starting with the second: l[1::2] :

l = [1, 8, 7, 2, 9, 18, 12, 0]

l[1::2] = l[::-2]
print(l)
#[1, 0, 7, 18, 9, 2, 12, 8]

CodePudding user response:

If you wanted to do it in a loop:

def flip_half(list):
    out = []
    for i in range(0,len(list)):
        if i % 2 != 0:
            out.append(list[-i])
        else: 
            out.append(list[i])
    return out

print(flip_half([1, 8, 7, 2, 9, 18, 12, 0]))

CodePudding user response:

If you need that elements with odd indexes has reverse order then one of next solutions (l - is your list):

Slices

l[1::2] = l[1::2][::-1]

List comprehension

l = [l[i] if i % 2 == 0 else l[-(i   len(l)%2)] for i in range(len(l))]

Function

def flip_half(lst):
    res= []
    for i in range(len(lst)):
        if i % 2 != 0:
            res.append(lst[-(i   len(lst) % 2)])
        else: 
            res.append(lst[i])
    return res

l = flip_half(l)

Generator function

def flip_half(lst):
    for i in range(len(lst)):
        if i % 2 != 0:
            yield lst[-(i   len(lst) % 2)]
        else: 
            yield lst[i]

l = list(flip_half(l))
  • Related