bungeegum
bungeegum

Reputation: 17

How to return the index of an element in a list of lists?

List = [[1,2,3],[4,5,6],[7,8,9]]

i want to pick a random element in List and return the index of it.

when I do:

List.index(random.choice(List[random.randint(0,2)]))

it obviously gives me an error, because the code only indexes the list-elements in List.

what I would like to have is something like:

output: The random number is: 4 and the index is: (1,0) or List[1][0]

Upvotes: 0

Views: 111

Answers (4)

THUNDER 07
THUNDER 07

Reputation: 559

Considering the given List as 2-d array i.e matrix

import random
# Userinput rows = int(input());matrix = [list(map(int,input().split())) for ctr in range(rows)]
matrix = [[1,2,3],[4,5,6],[7,8,9]]
rowIndex = random.randint(0, len(matrix) - 1)
colIndex = random.randint(0, len(matrix[rowIndex]) - 1)
print(f"The random number is: {matrix[rowIndex][colIndex]} and the index is: {(rowIndex, colIndex)} or matrix[{rowIndex}][{colIndex}]")

Upvotes: 0

bungeegum
bungeegum

Reputation: 17

I came up with this. I don't know if its convenient or not. I feel like there should be a better solution xD

tuple = (0, 0)
num = random.choice(List[random.randint(0,2)])
for i in List:
    if num in i:
        print(f"the random number is {num} and the index is {List.index(i), i.index(num)}")

output: the random number is 9 and the index is (2, 2)

Upvotes: 1

Sai Kiran
Sai Kiran

Reputation: 81

In the .index() section of python3.x list documentation you will see, index method returns "zero-based index in the list of the first item whose value is equal to search element". In your case all of the elements in the List are lists. To get the index of list containing the search number and the it's position in that list you will have to do something like this:

List = [[1,2,3],[4,5,6],[7,8,9]]
el = random.choice(List[random.randint(0,len(List))])
result = [(y, List[y].index(el)) for y, _ in enumerate(List) if (el in List[y])]

Upvotes: 1

asjhdbashjdbasjhdbhjb
asjhdbashjdbasjhdbhjb

Reputation: 68

This should work for any size list in List, not just size 3.

import random

List = [[1,2,3],[4,5,6],[7,8,9]]

rand1 = random.randint(0, len(List)-1)
rand2 = random.randint(0, len(List[rand1]-1))

print("The random number is: {} and the index is: {}".format(List[rand1][rand2], (rand1, rand2)))

Output: The random number is: 6 and the index is: (1, 2)

Upvotes: -1

Related Questions