1

I would like to make a program that will take a list:

myList = [a,b,c]

and be able to move all elements left or right, and drop anything that would be pushed out, replacing everything else with a 0:

moveRight(mylist) = [0,a,b]
moveLeft(myList) = [b,c,0]
Nachtara
  • 35
  • 1
  • 7

4 Answers4

3

Slicing is very helpful:

def moveRight(mylist, distance=1, pad=0):
    return ([pad] * distance) + mylist[:0 - distance]

def moveLeft(mylist, distance=1, pad=0):
    return mylist[distance:] + ([pad] * distance)

You could also do the change in-place:

def moveRight(mylist, distance=1, pad=0):
    mylist[:] = ([pad] * distance) + mylist[:0 - distance]

def moveLeft(mylist, distance=1, pad=0):
    mylist[:] = mylist[distance:] + ([pad] * distance)

Both ways, the default is to shift by one, but you could shift by any positive integer. You can also use something other than 0 to fill in the missing elements with.

zondo
  • 19,901
  • 8
  • 44
  • 83
3

You could slice the list to remove the relevant elements and add [0] to it:

def moveRight(mylist):
    return ['0'] + myList[:-1]

def moveLeft(mylist):
    return myList[1:] + ['0']
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

If you want the size of the collection to be preserved, use a deque from the collections module

from collections import deque

>>> d = deque(list(range(1, 6)), maxlen=5)
>>> d.append(0)
>>> d
deque([2, 3, 4, 5, 0], maxlen=5)
>>> d.appendleft(0)
>>> d
deque([0, 2, 3, 4, 5], maxlen=5)

deque also has extend and extendleft methods to add multiple elements at once.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
1

You can also make good use of deque from collections module in your case:

>>> from collections import deque
>>> 
>>> q = deque(maxlen=3)
>>>
>>> q.extend(['a','b','c'])
>>> 
>>> q
deque(['a', 'b', 'c'], maxlen=3)
>>> q.appendleft(0)
>>> q
deque([0, 'a', 'b'], maxlen=3)
>>> q.append(0)
>>> q
deque(['a', 'b', 0], maxlen=3)

The idea here is to keep the queue of fixed size so whenever you append an item from either right or left the item on the opposite end gets pushed out.

Quoting from Python Cookbook 3rd Edition :

Adding or popping items from either end of a queue has O(1) complexity. This is unlike a list where inserting or removing items from the front of the list is O(N).

Iron Fist
  • 10,739
  • 2
  • 18
  • 34