+ 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
7 ответов
+ 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)
+ 4
+ 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
- 1
#outputs:
[1, 2, 3]
[4, 5, 6]
#and
1
2
3
Sorry still didn't get it