Skip to content
Advertisement

Generating lists from other lists while keeping the order [closed]

I have a list in the form of [2, 1, 4, 3]. Is there a way to produce all of the possible sequences of the list values while keeping the same order? To further clarify, I am expecting something like this:

[1, 4, 3, 2], 
[4, 3, 2, 1], 
[3, 2, 1, 4],
[2, 1, 4, 3]

I would describe the problem as a case of “Reshuffling” but keeping the order constant, or imagining each of these sequences being circular, i.e. the final element in the list then becomes the first, etc. There are many ways to visualize this, hope it makes some sense.

Advertisement

Answer

>>> data = [4, 3, 2, 1]
[4, 3, 2, 1]
>>> l = len(data)
>>> for i in range(l):
...     print(data[l - i:] + data[0:l - i])
...
[4, 3, 2, 1]
[1, 4, 3, 2]
[2, 1, 4, 3]
[3, 2, 1, 4]

Or if we want to capture them rather than print them:

[data[len(data)-i:] + data[0:len(data)-i] for i in range(len(data))]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement