0

Suppose I have a bunch of elements in a long list and I want to switch them around based on the output I get in random.randit(lo,hi) function. For instance, my list is

L=[(1,hi), (1, bye), (1,nope), (1,yup), (2,hi), (2, bye), (2,nope), (2,yup), (3,hi), (3, bye), (3,nope), (3,yup), (4,hi), (4, bye), (4,nope), (4,yup), (5,hi), (5, bye), (6,nope), (7,yup)]

if I import from random import randint and then do randint(0,(len(L)-1))the number I get as an output I want to take the item indexed at that number and swap it with the last element in the list, and then randint(lo, len(L)-2)) and take the number that I get from that output, take the element indexed at that number and swap it with the second to last element and so on until I get to the beginning. It's like I want to rearrange the list completely random and not use the shuffle function.

**I understand that I can do randint(0,(len(L)-1)) and if I get 5 as an output do A=L[19] (because I know the last element in my list is indexed as 19). And then do L[19]=L[5] so that the 5th element takes the 19th elements place and then do L[5]=A so that what WAS the last element then becomes the 5th element. But I do not know how to write that as a loop.

python_newbie
  • 113
  • 1
  • 2
  • 8

2 Answers2

1
L =[(1,'hi'), (1, 'bye'), (1,'nope'), (1,'yup'), (2,'hi'), (2, 'bye'), (2,'nope'), (2,'yup'), (3,'hi'), (3, 'bye'),
   (3,'nope'), (3,'yup'), (4,'hi'), (4, 'bye'), (4,'nope'), (4,'yup'), (5,'hi'), (5, 'bye'), (6,'nope'), (7,'yup')]


   for i in range(-1, -len(L) -1 ,-1):
    n = randint(0,(len(L) -1))
    L[n], L[i]   =  L[i], L[n]


print(L)

output

[(2, 'nope'), (6, 'nope'), (3, 'hi'), (3, 'yup'), (2, 'bye'), (7, 'yup'), (1, 'hi'), (3, 'bye'), (3, 'nope'), (1, 'yup'), (1, 'bye'), (5, 'bye'), (4, 'yup'), (5, 'hi'), (4, 'bye'), (2, 'hi'), (2, 'yup'), (4, 'hi'), (1, 'nope'), (4, 'nope')]
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
0

You can use pop and append wrapped in a list comprehension structure to shuffle your list. You are then randomly popping an element from a shrinking list and appending to the end.

from random import randint

L = [(1, 'hi'), (1, 'bye'), (1, 'nope'), (1, 'yup'), 
     (2, 'hi'), (2, 'bye'), (2, 'nope'), (2, 'yup'), 
     (3, 'hi'), (3, 'bye'), (3, 'nope'), (3, 'yup'), 
     (4, 'hi'), (4, 'bye'), (4, 'nope'), (4, 'yup'), 
     (5, 'hi'), (5, 'bye'), (6, 'nope'), (7, 'yup')]

_ = [L.append(L.pop(randint(0, n))) for n in range(1, len(l) - 1)]
Alexander
  • 105,104
  • 32
  • 201
  • 196