Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search list in list written in Python

I have modified a simple search list in list (codes borrowed from another site) but unable to capture all the relevant information.

INPUT FILE :

data = [['a','b'], ['a','c'], ['b','d'],['a','b']]

I am searching the whole list with a 'b' in it but my algorithm only captures anything ending with a 'b'. I could not capture all 'b' whether it starts in Index(0) or Index(1).

data = [['a','b'], ['a','c'], ['b','d'],['a','b']]
search = 'b'
for sublist in data:
    if sublist[1] == search:
        print("Found it!" + str(sublist))

Below is the OUTPUT but it is missing ['b','d']. Could someone help please?

Found it!['a', 'b']
Found it!['a', 'b']

2 Answers

Just use in for membership check like,

>>> data = [['a','b'], ['a','c'], ['b','d'],['a','b']]
>>> for sub in data:
...   if 'b' in sub:
...     print(sub)
... 
['a', 'b']
['b', 'd']
['a', 'b']
like image 176
han solo Avatar answered Nov 24 '25 19:11

han solo


Try:

data = [['a','b'], ['a','c'], ['b','d'],['a','b']]
search = 'b'
for sublist in data:
    # Edited this part
    if search in sublist:
        print("Found it!" + str(sublist))

Output:

Found it!['a', 'b']
Found it!['b', 'd']
Found it!['a', 'b']
like image 27
Dipen Dadhaniya Avatar answered Nov 24 '25 18:11

Dipen Dadhaniya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!