nectarBee
nectarBee

Reputation: 401

To check whether at least one list contains a specific element

Could someone please tell me what is the shortest way to write this logic?

I have two lists as list_one and list_two containing some letters. If none of these two lists contain 'B', I need to print(True). The snippet I have written works, but I am curious to know whether there is a pythonic way to write this instead of  repeating 'B' twice in the same line.

    list_one = ['A', 'K', 'L', 'J']
    list_two = ['N', 'M', 'P', 'O']
    
    if 'B' not in list_one and 'B' not in list_two:
        print('True')

  Thanks in advance and any help would be greatly appreciated. 

Upvotes: 1

Views: 222

Answers (4)

Ruthger Righart
Ruthger Righart

Reputation: 4921

A different way of doing this is putting all lists in a Pandas DataFrame first:

import pandas as pd
df = pd.DataFrame(list(zip(list_one, list_two)), columns =['l1', 'l2']) 

Then you could check easily if the character B is absent by returning a True. The double .any() is to check rows and columns:

~df.isin(['B']).any().any()

Upvotes: 1

sekomer
sekomer

Reputation: 742

We have sets in Python and they are really fast compared to lists.

Here some features about sets.

  • Sets are unordered.
  • Set elements are unique.
  • Duplicate elements are not allowed in sets.

Therefore you can search the item in a common set.

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']

if 'B' not in set(list_one + list_two)
    print('True')

Bonus: You can use extend method to speed up list concatenation

set( list_one.extend( list_two ))

Upvotes: 1

Albin Paul
Albin Paul

Reputation: 3419

You can try the all function if it is more readable for you.

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']

print(all('B' not in current_list for current_list in [list_one, list_two]))

Upvotes: 2

Synthaze
Synthaze

Reputation: 6090

Well, you can do that (even though I think your way is the best):

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']
    
if 'B' not in (set(list_one) & set(list_two)):
    print('True')

Or:

if 'B' not in list_one + list_two:
        print('True')

Upvotes: 2

Related Questions