Jump to content

How can I create a shuffled list of integers in Python?


SubhanUllah

Recommended Posts

Randint() and shuffle are your friends here.

import random 
test_list = [random.randint(-100000, 100000) for i in range(300)] 
print(f"300 Random Ints \n{test_list}") 
# shuffle() mixes the list in place  
second_list = list(range(40)) 
random.shuffle(second_list) 
print(f"First 40 Ints shuffled \n{second_list}") 
# sample returns a new list and leaves the old one alone 
string_list = "Tell me and I forget, teach me and I may remember, involve me and I learn.  Benjamin Franklin".split() 
shuffled_words = random.sample(string_list,len(string_list)) 
print(f"Original words \n{string_list}") 
print(f"And sample() to shuffle\n{shuffled_words}") 

The random.randint() and range() creates a list of 300 numbers selected randomly, from -100,000 to 100,000. Just change the parameters to get what you want. The second shuffles any list not just Integers. Sample() also shuffles and existing list, but creates a new list.

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...