I want to shuffle the elements of a list without importing any module. The type of shuffle is riffle shuffle. Where you want to divide the no. of elements of the list into two and then interleave them.
if there are odd no. of elements then the second half should have contain the extra element
eg: list = [1,2,3,4,5,6,7]
then the final list should look like [1,4,2,5,3,6,7]
Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.
To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.
Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.
Just for fun, a recursive solution:
def interleave(lst1, lst2):
if not lst1:
return lst2
elif not lst2:
return lst1
return lst1[0:1] + interleave(lst2, lst1[1:])
Use it as follows in Python 2.x (In Python 3.x, use //
instead of /
):
lst = [1,2,3,4,5,6,7]
interleave(lst[:len(lst)/2], lst[len(lst)/2:])
=> [1, 4, 2, 5, 3, 6, 7]
The above will work fine with lists of any length, it doesn't matter if the length is even or odd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With