Print a list within a list by searching an element


I have a list of list like follows:

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

I want to input an element between a and d. Then search for the list that contains that element and print it, like this:

request = input('Input character: ')
if request in lists:
print() #list that contains the character the user inputted

So if the user inputs ‘a’, I want it to print the list [‘a’, ‘b’]. How can I do that?

Asked By: Ian Lohan




You can iterate over each of the lists using a for loop, then use in to determine if the user’s input is in the list, and then output that element.

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

request = input('Input character: ')

for element in lists:
  if request in element:

More info

For loops

The in operator on lists

Answered By: iteratedwalls
lists = [['a', 'b'], ['c', 'd']]
request = input('Input character: ')
for elem in lists:
    if request in elem:
        print(elem) #list that contains the character the user inputted
Answered By: bitflip
lists = [['a', 'b'],['c', 'd']]
keys = ['key1', 'key2']
dict = dict(zip(keys, lists))

while True:
    request = input('Input character: ')
    for keys, value in dict.items():
        for values in value:
            if request == values:
Answered By: Utku Can

In order to check if the value of request is within any of the elements in your lists,
you must first iterate through the list of lists.

Then, check if each selected element is in the current list.


    def get_list_with_element(element, list_of_lists):
        for current_list in lists:
            if(element in current_list):
                return current_list

    lists = [['a', 'b'],['c', 'd']]
    request = input('Input character: ')
    print("List found: ")
    print(get_list_with_element(request, lists))

Explanation of Solution:

  • first pass in the element you want to check, and the list of lists
  • loop through the list_of_lists
  • check each current list within list_of_lists
  • check if the element is in the current list, and if it is, return the current list


    Input character: a
    List found: 
    ['a', 'b']

What does the in keyword do?

You can use the in keyword to check whether a string exists within another string.

"The in operator works with iterable types, such as lists or strings, in Python. It is used to check if an element is found in the iterable. The in operator returns True if an element is found. It returns False if not"

I recommend that you read about loops and iteration in python, here is one helpful reference:


Answered By: Kelsey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.