+ 1

Why I'm facing this error in python, can someone explain please

Let's say we have this list m = [[1, 2, 3], [4, 5, 6]] and I want to check if the number 2 is inside this list so I wrote the following code: print( 2 in m) the output is False .However when I wrote: print(2 in m[0]) the output is True. So why the second code is working while the first is not

17th Mar 2022, 8:28 PM
Ahmad Anbar
Ahmad Anbar - avatar
4 Réponses
+ 6
Ahmad Anbar , we have to use an iteration with a for loop over all sub-lists (elements) in list m: m = [[1, 2, 3], [4, 5, 6]] found = False for lst in m: if 2 in lst: found = True print(found)
17th Mar 2022, 8:37 PM
Lothar
Lothar - avatar
+ 4
FF9900 ravilnicki Yones Mussa Lothar Thanks guys 👍 I think I got it now
17th Mar 2022, 8:52 PM
Ahmad Anbar
Ahmad Anbar - avatar
+ 2
It because you have a nested list. You are accessing the nested list when you check for 2 but when you do m[0] is checking the list inside the list
17th Mar 2022, 8:43 PM
Yones Mussa
- 1
#outputs: [1, 2, 3] [4, 5, 6] #and 1 2 3 Sorry still didn't get it
17th Mar 2022, 8:37 PM
Ahmad Anbar
Ahmad Anbar - avatar