0

Suppose, I have 3 Python lists

l1 = [2, 5, 2, 4, 1] 
l2 = [5, 1, 6, 3, 9] 
l3 = [4, 9, 1, 8, 4]

I want to get list name for which the corresponding index would have the lowest values.

Like for 0th index

l1 = 2, l2 = 4 and l3 = 4

In this case, after applying the min function I would get 2 as the answer. I want that instead of getting the value I want the list name from which it was selected(i.e l1 for this example)

I did try using min inside the for loop but that just gives minimum from the three lists and cannot get the list name

l1 = [2, 5, 2, 4, 1] 
l2 = [5, 1, 6, 3, 9] 
l3 = [4, 9, 1, 8, 4]

for i in range(len(l1)):
    print(min(l1[i], l2[i], l3[i]))

The output I got:

2 1 1 3 1

So, for the above example, the expected output would be l = [l1, l2, l3, l2, l1]

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208

1 Answers1

1

There is no clean and simple way to access the name of a variable in Python as a string. See Getting the name of a variable as a string for a discussion.

One way to achieve what you want is to store the names explicitly next to the list:

lists = [
    {
        'name': 'l1',
        'data': [2, 5, 2, 4, 1],
    },
    {
        'name': 'l2',
        'data': [5, 1, 6, 3, 9],
    },
    {
        'name': 'l3',
        'data': [4, 9, 1, 8, 4],
    },
]

for idx in range(len(lists[0]['data'])):
    compare = [
        li['data'][idx]
        for li
        in lists
    ]
    minval = min(compare)
    minidx = compare.index(minval)
    minname = lists[minidx]['name']
    print(minname)

Output

l1
l2
l3
l2
l1
Cloudomation
  • 1,597
  • 1
  • 6
  • 15