How to refer to a string as the name of a list?

Question:

Suppose there are 3 lists:

l_1 = ['a', 'b', 'c']
l_2 = ['d', 'e', 'f']
l_index = ['l_1', 'l_2']

So l_index contains names of 2 other lists. I want first to select a list by randomness, for which I can use:

import random
selected_list = random.choice(l_index)

Then I need to select an element in that list, also by randomness. However this doesn’t work:

selected_element = random.choice(selected_list)

It’s because selected_list is treated as a string. How can I make python refer to it as a list instead?

Asked By: NonSleeper

||

Answers:

You could contain the two lists themselves in another list, and then make a random selection from 0 to the number of lists minus one.

import random

l_1 = ['a', 'b', 'c']
l_2 = ['d', 'e', 'f']
lists = [l_1, l_2]
idx = random.randint(0, len(lists) - 1)
random_list = lists[idx]
selected_element = random.choice(random_list)
print(selected_element)  # prints from both lists over time
Answered By: Tim Biegeleisen

You should have a list of the variables as suggested in the other answer, but if you have to use strings to get the lists use locals() to get a dict with the variables names as keys

selected_list = random.choice(l_index)
random.choice(locals()[selected_list])
Answered By: Guy

You could do it like this:

from random import choice

l_1 = ['a', 'b', 'c']
l_2 = ['d', 'e', 'f']
l_index = [l_1, l_2] # note use of variable names - not strings
    
print(choice(choice(l_index)))
Answered By: Vlad

we can avoid using a variable that holds the list names.

from random import choice
l_1 = ['a', 'b', 'c']
l_2 = ['d', 'e', 'f']
print(choice(l_1 + l_2))
Answered By: lroth
import random
l_1 = ['a', 'b', 'c']
l_2 = ['d', 'e', 'f']
l_index = [l_1, l_2]
selected_list = random.choice(l_index)
selected_element = random.choice(selected_list)
print(selected_element)

Your code was totally fine but in l_index you used its element as string remove those quotes

WRONG ONE:

l_index = ['l_1', 'l_2']

RIGHT ONE:

l_index = [l_1, l_2]

else everything will be same

Answered By: Bhaskar Gupta
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.