0

Let's say I have a list: a = [1,1].

If I call a.index(1) it will always return 0.

Is there any pythonic way to return 0 or 1 in equal probabilities?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Enzo Dtz
  • 361
  • 1
  • 16
  • Does this answer your question? [How to find all occurrences of an element in a list](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) Then [How can I randomly select an item from a list?](https://stackoverflow.com/q/306400/843953) – Pranav Hosangadi Feb 13 '23 at 23:13
  • 1
    Does this answer your question? [Selecting random elements in a list conditional on attribute](https://stackoverflow.com/questions/33695580/selecting-random-elements-in-a-list-conditional-on-attribute) Or with numpy: https://stackoverflow.com/questions/50798508/get-random-element-on-condition – mkrieger1 Feb 13 '23 at 23:24

1 Answers1

-1

As stated here:

The syntax of the index method is: list.index(x[, start[, end]]).

It also says:

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

So a possible way could be the use of random as the start argument:

import random

a = [1, 1, 1, 1, 1, 1]

index_method = a.index(1)
index_method_with_start = a.index(1, random.randint(0, len(a) -1))

print(index_method, index_method_with_start)
Kyostenas
  • 27
  • 4