Sequence Shufflers: range and len

Some coding scenarios may require offsets in order to pull sequences apart and put them back together. The range integers provide a repeat count in the first, and a position for slicing in the second.

>>> a = 'developer'
>>> for i in range(len(a)):
...     a = a[1:] + a[:1]
...     print(a, end = ' ')
... 
eveloperd veloperde eloperdev loperdeve operdevel perdevelo erdevelop rdevelope developer >>> 
>>> 
>>> a
'developer'
>>> for i in range(len(a)):
...     b = a[i:] + a [:i]
...     print(b, end = ' ')
... 
developer eveloperd veloperde eloperdev loperdeve operdevel perdevelo erdevelop rdevelope >>>

Note:

  • The second creates the result in a different order.
  • The second doesn’t change the original variable as it goes.
  • They work on any type of sequence, and return sequences of the same type.

Code like this can be used to test functions with different argument orderings for example. It’s a very useful tool.

Leave a Reply