Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
shuffle a nested list
#11
random.shuffle() is a function that only produces a side effect. The items in the provided list are shuffled. random.shuffle() does not create a list. random.shuffle does not return a list (it returns None).

If you want to use random.shuffle you need to first create you list of lists, then you can shuffle each list.
import random

def randomlist(values, count):
    retval = [values for _ in range(count)]
    for values in retval:
        random.shuffle(values)
    return retval

print(randomlist([1,2,3], 8))
random.sample can be used to create a shuffled list. Unlike shuffle() it creates a new list. This allows creating the lists and shuffling in a single step.
def randomlist(values, count):
    return [random.sample(values, k=len(values)) for _ in range(count)]
Reply
#12
(Nov-12-2020, 05:43 PM)giorgosmarga Wrote: Ohh i got it thank you very much.But is there a way to do what i want to do?

Actually I don't know what you want to do Smile .

But maybe you want something along those lines:

>>> nums = list(range(5))
>>> [random.sample(nums, len(nums)) for i in range(5)]
[[0, 3, 4, 2, 1],
 [2, 1, 0, 4, 3],
 [3, 0, 4, 2, 1],
 [2, 3, 1, 0, 4],
 [3, 0, 1, 2, 4]]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List all possibilities of a nested-list by flattened lists sparkt 1 922 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Updating nested dict list keys tbaror 2 1,290 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Python Program to Find the Total Sum of a Nested List vlearner 8 4,938 Jan-23-2022, 07:20 PM
Last Post: menator01
  Looping through nested elements and updating the original list Alex_James 3 2,145 Aug-19-2021, 12:05 PM
Last Post: Alex_James
Question Save list with nested list into CSV SpongeB0B 1 5,394 Oct-12-2020, 07:26 AM
Last Post: bowlofred
  Struggling with nested list gr3yali3n 3 2,332 Jul-09-2020, 05:30 PM
Last Post: DPaul
  Nested Dictionary/List tonybrown3 5 3,174 May-08-2020, 01:27 AM
Last Post: tonybrown3
  Help removing asterisk item in a nested list. bmcguire 3 2,607 Apr-06-2020, 02:35 PM
Last Post: snippsat
  Make nested system directories based on an unsorted list? koebi 0 1,600 Mar-25-2020, 01:14 PM
Last Post: koebi
  list approach due nested order 3Pinter 6 2,848 Oct-07-2019, 01:49 PM
Last Post: 3Pinter

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020