3

i want to ask if i got a array of list in python like this:

a = [[1, 2, 3, 4, 5, 6], 
     [1, 2, 3, 4, 5, 6],
     [1, 2, 3, 4, 5, 6]]

How do i shuffle within range a[1][1] to a[1][4]?

I only know the normal shuffle

random.shuffle(a)
Mazdak
  • 105,000
  • 18
  • 159
  • 188

2 Answers2

7

Take a sample from the sublist, with the sample size set to the same length, then assign that sample back to the slice:

a[1][1:4] = random.sample(a[1][1:4], 3)

This takes a sample of the 3 elements from the source list (producing those same 3 elements in random order), and assigns these right back to the same indices.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

For reference, in case you want to use shuffle you can follow the same approach given by Martijn, but it requires to assign the slice to a name, since shuffle mixes things in place

>>> s=a[1][1:4]
>>> s
[2, 3, 4]
>>> shuffle(s)
>>> s
[4, 2, 3]
>>> a[1][1:4] = s
>>> a
[[1, 2, 3, 4, 5, 6], [1, 4, 2, 3, 5, 6], [1, 2, 3, 4, 5, 6]]
Pynchia
  • 10,996
  • 5
  • 34
  • 43