Home > OS >  Identifying lists in Python
Identifying lists in Python

Time:01-06

I have, for example 4 lists

list1 = [orange, banana, banana]
list2 = [orange, orange, orange]
list3 = [banana, orange, orange]
list4 = [banana, banana, orange]

and my main list is, for example

MainList = [orange, banana, banana]

is there a way to match, In this example MainList and List1 cause they are same? instead of doing

If Main list == list1:
 elif.....etc.

I tried it with manually checking every list with stacking if statements, but there must be a better way.

CodePudding user response:

Any time you are naming variables things like list1, list2 it's an indication that those things should be in a list of their own. If you do that, you can check for MainList in one line:

fruitlists = [
    ["orange", "banana", "banana"],
    ["orange", "orange", "orange"],
    ["banana", "orange", "orange"],
    ["banana", "banana", "orange"]
]

MainList = ["orange", "banana", "banana"]    
MainList in fruitlists
# True

OtherList = ["banana", "banana", "banana"]
OtherList in fruitlists
# False

fruitlists.index(["banana", "banana", "orange"])
# 3
# ...etc.

Now instead of list1, list2 you would use fruitlists[0], fruitlists[1], etc. This will be much more maintainable and easier to code than a whole bunch of similarly-named variables.

CodePudding user response:

Actually, it is very easy:

list1 = ["orange", "banana", "banana"]
MainList = ["orange", "banana", "banana"]
print(list1 == MainList)

Output: True

CodePudding user response:

Put every lists in a single list and loop it example:

total_list = [[orange, banana, banana],[orange, orange, orange],[banana, orange, orange]]

for i in total_list:
   if mainlist == i

CodePudding user response:

Yes one possible option is adding all your lists to a list. Then you loop thrue the list of lists until its the same as Mainlist.

Your reselt will give the index off the the mainlist in the list of lists.

list = [["orange", "banana", "banana"],
        ["orange", "orange", "orange"],
        ["banana", "orange", "orange"],
        ["banana", "banana", "orange"]]

MainList = ["orange", "banana", "banana"]


for i in list:
    if i == MainList:
        print(f'index{list.index(i)}')

Expected awnser is

index 0

CodePudding user response:

match mainlist:
    case list1:
        #do something or pass
    case list2:
        #do something or pass
    case list3:
        #do something or pass
    case list4:
        #do something or pass
  • Related