Chief C
Chief C

Reputation: 51

How can you create a list of lists while swapping numbers

Let's say I have a list of numbers

L1 = [1,2,3]

I want to be able to generate many lists from this list while swapping the numbers.

L1 = [1,2,3] 
L2 = [2,1,3]
L3 = [3,2,1]
L4 = [1,3,2]

What is the best way to do this?

Upvotes: 1

Views: 47

Answers (2)

Dharmesh Fumakiya
Dharmesh Fumakiya

Reputation: 2338

from itertools import permutations
L1 = [1,2,3]
for p in permutations(L1):
    print list(p)

output:

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

Upvotes: 2

Serjik
Serjik

Reputation: 10931

from itertools import permutations

print(list(permutations(L1)))

While give you a list of what you want

Upvotes: 4

Related Questions