0

i have a list with 9000 list items as strings, i want to select 4000 instances randomly amongst them. how can i achieve this. I have write down a code.

from random import randint
for r in range(9000):
    print(randint(9000))
  1. first i will generate the random 4000 random number
  2. and then list members will be picked up by the selected random numbers I have write down a code which is showing an error code is as given bellow
3
  • 1
    With or without duplicates? random.sample could help if you want to select k random items out of all possible items. Commented Mar 3, 2016 at 16:09
  • have you read the documentation on the random module? Do any of the functions it provides answer your question? Commented Mar 3, 2016 at 16:10
  • random.shuffle and list splicing could be useful depending on what you want to do with the info Commented Mar 3, 2016 at 16:11

2 Answers 2

1

use random.sample

from random import sample

my_list = [1,2,3,4,5,5,4]

print(sample((my_list), 5)) # you would change 5 to 4000

As a side note If you want to remove duplicates from your result you can use a set as sets in python don't allow duplicate items, another example

my_list = [1, 2, 3, 4, 5, 5, 4, 6, 5, 3, 2, 12]

result = set(sample((my_list), 5)) # you would change 5 to 4000
print(result)

#set might remove duplicates so you wont have the desired number of items again
while len(result) < 5: # length of your list
    rand = choice(my_list)
    result.add(rand)

print(result)
Sign up to request clarification or add additional context in comments.

2 Comments

I wouldn't recommend using set here. For example, if the original list does not contain 4,000 unique values, it will never exit the loop. I.E. if the list contains only 1's and 0's, you will only get a set of {[0, 1]} or {[1, 0]} and adding a 1 or 0 to it will never increase the length. I recommend sample.
@Goodies....that's a very good observation...when I get back to my pc I'll edit my answer...and lay emphasis on that
0

It is very simple.Try something like this

import random
for x in range(100):
  print random.randint(100,150)*2,
print

Then you get

290 268 200 266 238 284 220 246 294 226 208 268 298 206 210 260 206 250 264 290 298 212 262 258 222 272 298 226 248 260 278 254 236 296 264 224 240 246 220 210 232 242 240 272 276 272 240 256 242 252 202 234 280 216 238 290 236 258 262 208 236 252 254 238 276 256 220 266 258 258 202 250 262 204 252 218 242 276 222 218 262 290 286 300 262 202 228 218 248 202 264 226 242 208 220 224 238 240 236 250

So just choose your range.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.