How to do a Circular left shift for a byte in python

Question:

I am trying to do a left-byte shift on a list.
But it is not working properly.

def left_byte_shift(w3):
    temp = w3
    x=0
    a = (len(w3)-1) 
    print("a=",a)
    
    for i in reversed(range(len(w3))):
        if i == a: #3 
            w3[x] = temp[a]
        else:    #2,1,0

            print(w3[i],temp[i+1])
            w3[i] = temp[i+1]
            print(w3[i],temp[i+1],'nn')

    return w3 

1

Asked By: Sameer Khan

||

Answers:

I think this is what you’re looking for?

w = [1, 2, 3, 4]
w[-1], w[:-1] = w[0], w[1:]
print(w) # [2, 3, 4, 1]

It’s not exactly a left "byte" shift, more like a left element shift.

Answered By: pwasoutside

If the list has exactly 4 values as in the example:

wrot = [w[1], w[2], w[3], w[0]]

or for any non-empty list:

wrot = w[1:] + [w[0]]

In the examples above a new list is created. There is also an option to rotate the list in-place:

w.append(w.pop(0)) # remove the first item and append it at the end

If there are many shifts and rotations to be made, use a double-ended queue instead of a list, it is much more efficient.

Answered By: VPfB
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.