0

I have a nested loop. I want to iterate on a list of lists and check if a parameter is in a list, bring me back the list index.

parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]
for i in Li:
    for j in i:
        if (parameter==j):
            x=i+1
print(x)

I expect an integer like for this example x=2. But it does not work. How can I do that?

3
  • 2
    What do you expect print(Area) to output? You never defined that name... And what do you expect i+1 to be when i is a string?
    – trincot
    Commented May 25, 2022 at 15:59
  • Try to use for j in range(len(i)) and you will get the index you want
    – user16836078
    Commented May 25, 2022 at 16:00
  • Should the list your looping through be flattened? As it is youre getting the list the parameter belongs to but not the position in that list... Commented May 25, 2022 at 16:08

4 Answers 4

1

You didn't specify the output you are expecting, but I think you want something like this:

parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]
for row in Li:
    for i, j in enumerate(row):
        if parameter == j:
            print("List", Li.index(row),"Element", i)

Output:

List 1 Element 0
0

Use enumerate, which returns the index and the element. Also use sets, which are faster than lists (for long lists).

parameter = "Abcd"
lst1 = ["ndc", "chic"]
lst2 = ["Abcd", "cuisck"]
lst = [lst1, lst2]
x = None

for i, sublst in enumerate(lst):
    if parameter in set(sublst):
        x = i+1
print(x)
# 2       
2
  • Sets are unordered and can't have duplicates, so they're not a drop in replacement, depending on exactly what you're trying to do.
    – Donnie
    Commented May 25, 2022 at 16:13
  • @Donnie: That's true, but for the exact problem in the OP sets are a good solution. If lists are preferred (perhaps for small lists), then simply use them like this: if parameter in sublst: Commented May 25, 2022 at 16:19
0

Use numpy array. It will save you tons of time and cost.

Li = np.array([li1,li2])

Li == parameter

array([[False, False],
       [ True, False]])

row, column = np.where(Li == parameter)

row
Out[17]: array([1], dtype=int64)
0
parameter="Abcd"
li1=["ndc","chic"]
li2=["Abcd","cuisck"]
Li=[li1,li2]

index = -1

for i in Li:
    if parameter in i:
        index = Li.index(i)
            
print(index)

You can check if something is in a list with 'in' and get the index of the element with .index, it returns the integer position in the list. Perhaps you want a tuple for the nested position ? use something like (Li.index(i), i.index(parameter)) as your return value. Don't forget to declare your return value outside your loop scope !

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