If you only want to know if any item of d is contained in paid[j], as you literally say:

if any(x in paid[j] for x in d): ...

If you also want to know which items of d are contained in paid[j]:

contained = [x for x in d if x in paid[j]]

contained will be an empty list if no items of d are contained in paid[j].

There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

firstone = next((x for x in d if x in paid[j]), None)

BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

Answer from Alex Martelli on Stack Overflow
Top answer
1 of 4
59

If you only want to know if any item of d is contained in paid[j], as you literally say:

if any(x in paid[j] for x in d): ...

If you also want to know which items of d are contained in paid[j]:

contained = [x for x in d if x in paid[j]]

contained will be an empty list if no items of d are contained in paid[j].

There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

firstone = next((x for x in d if x in paid[j]), None)

BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

2 of 4
12

I assume you mean list and not array? There is such a thing as an array in Python, but more often than not you want a list instead of an array.

The way to check if a list contains a value is to use in:

if paid[j] in d:
    # ...
🌐
Swarthmore College
cs.swarthmore.edu › ~knerr › teaching › f17 › topics › strlist.html
Python Strings and Lists -- Quick Reference
This time we again convert i to a string, then add it as a list ([str(i)]) to the existing list, then assign back to the original variable. It's klunky, but it works (again, see append() below for a better way). Strings are encoded using the ascii encoding scheme. This just means a numeric value is assigned to each possible character (+,-./0123....ABCD...XYZ...abcd...xyz...). When you compare strings, they are compared by these numeric values.
Discussions

Python comparing a string or list of strings to a string or list - Code Review Stack Exchange
I'm using a selfmade python program for learning new words in new languages. Originally I made this program for a university course but now I'm just trying to imrove it and make the code "prettier"... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 1, 2016
Python compare part of string to list - Stack Overflow
I have multiple strings that looks like this: “BPBA-SG790-NGTP-W-AU-BUN-3Y” I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is fo... More on stackoverflow.com
🌐 stackoverflow.com
Faster Way of Comparing String to Large List of Strings
Hi. So I’m currently working on a moderation system for my Discord bot. The system has a function where it compares words in a message to all the possible Leetspeak variants of the blocked word that are contained in a list. The problem I’m having is I basically need to compare each word ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
5
0
February 27, 2024
How do I compare string in an list?
As a starting point to compare the first and last items (not just strings) of the list do List[0] == List[-1]. More on reddit.com
🌐 r/learnpython
7
0
January 24, 2023
🌐
Reddit
reddit.com › r/learnpython › how to compare if a string value in one list is another list?
r/learnpython on Reddit: How to compare if a string value in one list is another list?
March 28, 2022 -

I have a case where two lists might looks like this

A = [ABC, DEF, GHI] B = [ABC, LMN]

And I want to return TRUE if any of list A is in list B. So the above case should be TRUE but the below case should be false.

A = [ABC] B = [BCD]

All methods I find online would result in the second case being TRUE because the letters 'B' and 'C' are shared in the two lists. However, I want to treat the string as a whole and not compare individual letters.

Is there a way to do this? Appreciate any help!

🌐
EyeHunts
tutorial.eyehunts.com › home › python compare two lists of strings | examples
Python compare two lists of strings | Examples
October 26, 2022 - If the string list same then the list has zero elements. list1 = ['A', 'B', 'C'] list2 = ['A', 'C', 'B'] res = [x for x in list1 + list2 if x not in list1 or x not in list2] print(res) ...
Top answer
1 of 1
3

In your file reading part:

Use the with .. as construct

Use

with open(file, "r", encoding="UTF-8") as words_file:
    for line in words_file:

This will ensure that the file will be closed at the end.

split is more awesome than you think

>>> "abc".split(",")
["abc"]

So there is no need to check whether there is a "," in there. Note that both this and your original code will not strip the spaces after ":" and ",", if you enter for example:

foreign_word: native_word1, native_word2

So you might have to do something like this at the end:

foreign = [word.strip() for word in foreign]

You can also directly assign the read foreign_words to the class, no need for the intermediary list:

self.__foreign_words.append(foreign.split(","))
self.__native_words.append(native.split(","))

list.append() is also faster than list += other_list

From the code you posted I don't see any reason to have this in the file reading part:

x = random.randint(0, (len(self.__foreign_words) - 1))
self.__index.set(x)

Because in the second part of the code you immediately set x as well.


In your second part:

if language == "F":
    correct_word = self.__native_words[x]
elif language == "N":
    correct_word = self.__foreign_words[x]

Can be simplified to

# In the class add this member
self.dictionary = {"F": self.__native_words, "N": self.__foreign_words
...
# Then you can just use later
correct_word = self.dictionary[language][x]

Instead of putting everything in an if block to make sure there are words to process, you could do:

assert(L>0)
# or
if L==0:
    exit() # or continue if you are in a loop
# Rest of code

join is more awesome than you think

>>> ", ".join(["abc"])
'abc'

So no need to check for isinstance(words,str), just use:

self.__question.set(", ".join(correct_word))

But I would not do this, because if you leave your correct_word as a list of correct words (possibly containing only one word, which is fine), then checking for the right answer becomes what you want:

if answer in correct_words:
    # Do stuff

When checking whether the list is still not empty, it is better to set L to the new length:

L = len(self.__foreign_words)
if L > 0:
    # Do stuff

Instead of

if L - 1 > 0:
    # Do Stuff

This way you can wrap this in a while loop more easily and repeat until the user quits or has finished all words. Your current code seems to only support asking for two words in a row.

🌐
PyTutorial
pytutorial.com › how-to-compare-two-lists-in-python
PyTutorial | Simplest ways to compare two lists of strings in python
January 10, 2023 - # Lists list_1 = ['a', 'b', 'c'] list_2 = ['q', 's', 'c'] # Check if both lists are similar if list_1 == list_2: print(True) else: print(False) ... There are many ways to get duplicated items in two lists, but we'll focus on the simple way in ...
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › compare two lists of strings in python (5 examples)
Compare Two Lists of Strings in Python (Example) | Return Match
September 5, 2023 - This tutorial shows how to find similarities and dissimilarities between two string lists in Python programming. The article consists of five examples explaning string list comparison.
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › programming › python
Faster Way of Comparing String to Large List of Strings - Python - The freeCodeCamp Forum
February 27, 2024 - Hi. So I’m currently working on a moderation system for my Discord bot. The system has a function where it compares words in a message to all the possible Leetspeak variants of the blocked word that are contained in a list. The problem I’m having is I basically need to compare each word in the message to well over the 42 million variants in the list in under- at the maximum- three seconds.
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › compare list & string in python (2 examples)
Compare List & String in Python (Examples) | Test Equality of Items
July 7, 2023 - In this tutorial, we explored different methods to compare a list and a string in Python. We learned how to check the existence of numerical and string elements of a list in a string.
🌐
Miguendes
miguendes.me › python-compare-lists
The Best Ways to Compare Two Lists in Python
July 2, 2022 - Learn to compare if two lists are equal, find elements that match, get the difference between 2 lists, compare lists of dictionaries, and list of strings.
🌐
Rosetta Code
rosettacode.org › wiki › Compare_a_list_of_strings
Compare a list of strings - Rosetta Code
June 2, 2026 - Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible. Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers. If you need further guidance/clarification, see #Perl and #Python for solutions that use implicit short-circuiting loops, and #Raku for a solution that gets away with simply using a built-in language feature.
🌐
Stack Overflow
stackoverflow.com › questions › 39682927 › comparing-element-in-list-and-string
python - Comparing element in list and string - Stack Overflow
September 25, 2016 - The problem is that after I change every line into a list then compare every element in a list to user input (What i have to search) problem is that even though element in list and user input match exactly the program does not recognize them as same thing... python · string-comparison ·
🌐
Stack Abuse
stackabuse.com › comparing-strings-using-python
Comparing Strings using Python
June 21, 2023 - The output is as follows, and matches "Bayswater", "Table Bay", and "Bombay" from the list of places: $ python3 comparing-strings-re.py Bayswater matches the search pattern Table Bay matches the search pattern Bombay matches the search pattern · So far our comparisons have only been on a few words. Using the difflib module Python also offers a way to compare multi-line strings, and entire lists of words.
🌐
YouTube
youtube.com › watch
List like types | List vs String | Compare list and string ...
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
🌐
Sololearn
sololearn.com › en › Discuss › 2487154 › how-do-i-compare-each-and-every-character-of-a-string-in-a-list-of-strings-in-python
How do I compare each and every character of a string in a list of strings in python | Sololearn: Learn to code for FREE!
September 9, 2020 - To make sure that i got it right: lst = ['abc','cfb','xac'] # list of strings # result: a found in xac b found in cfb c found in cfb c found in xac ... You need a 2d for loop. Outer loop may iterate through the string and inner loop may iterate through the list: for c in string: for s in list: #c is each character in the string #s is each string in the list #Now you can compare them here.