5

I have a file which contains a number of lists. I want to access the index of the values retrieved from each of these lists. I use the random function as shown below. It retrieves the values perfectly well, but I need to get the index of the values obtained.

for i in range(M):
           print(krr[i])
           print(krr[i].index(random.sample(krr[i],2)))
           nrr[i]=random.sample(krr[i],2)

           outf13.write(str(nrr[i]))
           outf13.write("\n")

I got ValueError saying the two values retrieved are not in the list even though they exist...

1
  • Could you post the full stacktrace of the IndexError to give more details
    – El Bert
    Mar 19, 2015 at 10:28

4 Answers 4

7

To retrieve the index of the randomly selected value in your list you could use enumerate that will return the index and the value of an iterable as a tuple:

import random
l = range(10) # example list
random.shuffle(l) # we shuffle the list
print(l) # outputs [4, 1, 5, 0, 6, 7, 9, 2, 8, 3]
index_value = random.sample(list(enumerate(l)), 2)
print(index_value) # outputs [(4, 6), (6, 9)]

Here the 4th value 6 and 6th value 9 were selected - of course each run will return something different.

Also in your code you are printing a first sample of the krr[i] and then sampling it again on the next line assigning it to nrr[i]. Those two calls will result in different samples and might cause your IndexError.

EDIT after OP's comment

The most explicit way to then separate the values from the indexes is:

indexes = []
values = []
for idx, val in index_value:
    indexes.append(idx)
    values.append(val)
print indexes # [4, 6]
print values # [6, 9]

Note that indexes and values are in the same order as index_value.

1
  • thnk uu ....it works!...but since I have to write the values to a file without the index which I have to use further ...can u tell me how to extract the index values only....
    – Devi
    Mar 21, 2015 at 7:11
3

If you need to reproduce the results, you can seed the random generator, for instance with random.seed(123). This way, every time you run the code you get the same random result.

In this case, the accepted solution offered by bvidal it would look like this:

import random
l = list(range(10)) # example list (please notice the explicit call to 'list')
random.seed(123)
random.shuffle(l) # shuffle the list
print(l) # outputs [8, 7, 5, 9, 2, 3, 6, 1, 4, 0]
index_value = random.sample(list(enumerate(l)), 2)
print(index_value) # outputs [(8, 4), (9, 0)]

Another approach is to use the random sample function random.sample from the standard library to randomly get an array of indices and use those indices to randomly choose elements from the list. The simplest way to access the elements is converting the list to a numpy array:

import numpy as np
import random
l = [1, -5, 4, 2, 7, 4, 8, 0, 9, 3]
print(l) # prints the list
random.seed(1234) # seed the random generator for reproducing the results
random_indices = random.sample(range(len(l)), 2) # get 2 random indices
print(random_indices) # prints the indices
a = np.asarray(l) # convert to array
print(list(a[random_indices])) # prints the elements

The output of the code is:

[1, -5, 4, 2, 7, 4, 8, 0, 9, 3]
[7, 1]
[0, -5]
1

You could try using enumerate() on your list objects.

According to the Python official documentation

enumerate() : Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence

A simple example is this :

my_list=['a','b','c']

for index, element in enumerate(my_list):
    print(index, element)

#    0 a
#    1 b
#    2 c

Don't know if I understood the question though.

0

You are getting the random sample twice, which results in two different random samples.

1
  • ..True ..thnks for the suggestion
    – Devi
    Mar 21, 2015 at 7:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.