-2

So, I have 3 possibilities of a list:

list_a = ['DU', "CARTE", 'AN', 'NM', 'DAN', 'DATE', '161', 'EUL', "Date", 'Latte', 'ZEBRA', 'M']
list_b = ['DU', "CARTE", 'AN', 'NM', 'DAN', 'DATE', '161', 'EUL', "Date", 'Latte', 'ZEBRA', 'F']
list_c = ['DU', "CARTE", 'AN', 'NM', 'DAN', 'DATE', '161', 'EUL', "Date", 'Latte', 'ZEBRA']

i.e. the list will either contain a 'M', a 'F' or it will not contain either of these 2. Also, if it contains 'M', it will not contain 'F' and vice versa! (they can be in any index position in list)

I have to find out, whether list contains 'M' or 'F' or not? If it does, I want it to assign/return what it contains - 'M','F' or None.

Currently I am doing:

for i in range(len(given_list)):
    if given_list[i] == "M" or given_list[i] == "F":
        answer = given_list[i]
        break

I feel this can be done in a much better, pythonic way. Can anyone help me out on this?

raghavsikaria
  • 867
  • 17
  • 30
  • If it's always going to end with one of those characters then you can just check `given_list[-1]` instead. – Loocid Sep 30 '20 at 05:26
  • 2
    There's no need to loop on the list indices. Just `if 'M' in lst or 'F' in lst:` – Thierry Lathuille Sep 30 '20 at 05:26
  • No it does not, like I mentioned, `they can be in any index position in list` – raghavsikaria Sep 30 '20 at 05:27
  • Use `in` to find if element exist in list. `if 'M' in given_list` etc – Yossi Levi Sep 30 '20 at 05:27
  • @ThierryLathuille but then, how do you I know which one matched and then assign it? – raghavsikaria Sep 30 '20 at 05:27
  • @YossiLevi, if I do that, I'll have to put that statement twice, which means iterating twice. – raghavsikaria Sep 30 '20 at 05:28
  • 1
    You can use list comprehension as well like `[item for item in given_list if item=="F" or item=="M"]`, then check - if list is empty return `None` otherwise return the only element in list. It will iterate only once in a more fancy pythonic way, that btw are much faster than regular looping over list. – Yossi Levi Sep 30 '20 at 05:38
  • Lol, after using list comprehension so much, how did this even escape my mind! Thanks. Check @blhsing 's answer, it's the best! – raghavsikaria Sep 30 '20 at 05:44

2 Answers2

1

You can use next with a generator expression that filters the list by testing if the items are one of the desired values, and default to None if none is found:

next((i for i in given_list if i in ('M', 'F')), None)
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

If u definitely want to iterate over the list, then use list comprehension.

answer = [given_list[i] for i in range(len(given_list)) if given_list[i] == "M" or given_list[i] == "F"]
   
if answer == []:
    answer = None

print(answer)
Sushil
  • 5,440
  • 1
  • 8
  • 26