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:
    # ...
🌐
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!

Discussions

Python comparing a string or list of strings to a string or list - Code Review Stack Exchange
Currently it just works if I type the whole word with the commas included or if it's not separated by the commas in the first place. How could I compare the answer to the single word (string), or if it's a list of two or three words, check if at least one of them is correct? More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 1, 2016
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
python - How does one compare a string to the next string in a list? - Stack Overflow
I'm writing a small NLP algorithm and I need to do the following: For every string x in the list ["this", "this", "and", "that"], if the string x and the next string are identical, I want to prin... More on stackoverflow.com
🌐 stackoverflow.com
June 10, 2016
string - Comparing two lists in Python - Stack Overflow
How would I go about doing it to check a total of say.. 5 strings at the same time? 2012-07-28T02:43:16.63Z+00:00 ... @Matthew You could extend this example to more lists, zip can handle more than two lists, e.g., for i,j,k in zip(aa, bb, cc): print i, j, k .. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 ...
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.

🌐
EyeHunts
tutorial.eyehunts.com › home › python compare two lists of strings | examples
Python compare two lists of strings | Examples
October 26, 2022 - import collections list1 = ['A', 'B', 'C'] list2 = ['A', 'D', 'E'] if collections.Counter(list1) == collections.Counter(list2): print("Both List are same") else: print("Not the same")
🌐
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'] new_list = [] # Iterate Over list_1 for i in list_1: # Check if item exist on list_2 if i in list_2: # Append to new_list new_list.append(i) # Print new_list print(new_list)
🌐
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 - As it will be seen soon, an if-else statement is used to make this comparison. if list1 == list2: # test if identical print("The lists are the same!") else: print("The lists are different!") # The lists are different!
🌐
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.
Find elsewhere
🌐
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 - Check if two lists are equal, which elements match, get the difference between two lists, compare lists of dictionaries, list of strings and more! UpdatedJuly 2, 2022•17 min read•View as Markdown ... AI Software Engineer based in London, UK with 6+ years of professional experience developing and releasing software in different programming languages - Hobbyist Technical Writer - Interested in Software Testing, Best Practices, Scalability, Machine Learning/AI, and Python.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-compare-two-lists-in-python
How to Compare Two Lists in Python | DigitalOcean
July 22, 2025 - This article will cover the primary methods for comparing two lists in Python. We’ll explore practical techniques for different comparison goals, from simple equality checks to finding unique elements. You’ll learn how to check for exact equality (content and order) using the == operator, and how to verify if lists have the same elements regardless of order with sorted() and collections.Counter.
🌐
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 - 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.
🌐
Note.nkmk.me
note.nkmk.me › home › python
String Comparison in Python (Exact/Partial Match, etc.) | note.nkmk.me
April 29, 2025 - Its usage is the same as startswith(). ... print(s.endswith(('aaa', 'bbb', 'ccc'))) # True ... You can compare strings with the <, <=, >, and >= operators, just like numbers....
🌐
Rosetta Code
rosettacode.org › wiki › Compare_a_list_of_strings
Compare a list of strings - Rosetta Code
June 2, 2026 - Application code is hard to write and hard to read when low-level code is mixed in with application code. It is better to hide low-level code in general-purpose code-libraries so that the application code can be simple. Here is my solution using LIST.4TH from my novice-package: https://www.forth2020.org/beginners-to-forth/a-novice-package · : test-equality ( string node -- new-string bad? ) over count \ -- string node adr cnt rot .line @ count compare ; : test-ascending ( string node -- new-string bad?
🌐
Stack Abuse
stackabuse.com › comparing-strings-using-python
Comparing Strings using Python
June 21, 2023 - This order depends on the character table that is in use on your machine while executing the Python code. Keep in mind the order is case-sensitive. As an example for the Latin alphabet, "Bus" comes before "bus". Listing 2 shows how these comparison operators work in practice. ... # Define the strings listOfPlaces = ["Berlin", "Paris", "Lausanne"] currentCity = "Lausanne" for place in listOfPlaces: if place < currentCity: print (f"{place} comes before {currentCity}") elif place > currentCity: print (f"{place} comes after {currentCity}") else: print (f"{place} is equal to {currentCity}")
🌐
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... ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags.