Coder20
Coder20

Reputation: 65

How to return a list which contains certain element from lists of lists

Is there a more efficient way to return a list that contains a certain element from a list of lists?

For example:

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]

If my input is C return the list ['C'] or if my input is D return the list = ['A', 'B', 'D', 'E', 'F', 'G', 'H']

What I've tried:

for lst in lists: 
    for n in range(len(lst)):
        if element == lst[n]:
            print(lst)

This is inefficient and I would like to know how to make it more efficient.

Upvotes: 0

Views: 1328

Answers (5)

Grzesik
Grzesik

Reputation: 151

Your welcome:

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]
element ='D'
lst = [lst for lst in lists if element in lst]
print(lst)

Upvotes: 0

ᴇɴᴅᴇʀᴍᴀɴ
ᴇɴᴅᴇʀᴍᴀɴ

Reputation: 384

You should use the in operator:

def foo(lists, element):
    for l in lists:
        if element in l:
            return l
print(foo([['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']], 'C')) #prints ['C']
print(foo([['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']], 'D')) #prints ['A', 'B', 'D', 'E', 'F', 'G', 'H']

Let me know if that helped!

Summary of answer: I used a function with parameters as the list, and the element. Basically I looped through each list in the list of lists, and checked if the element is in each list. If so, I return that list.

Upvotes: 0

Murali S
Murali S

Reputation: 61

You can try this.

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]

user_input = input("Please enter your input: ")

for item in lists:
    if user_input in item:
        print(item)
        break

Upvotes: 0

Oleksandr Lisovyi
Oleksandr Lisovyi

Reputation: 41

You can try this:

for lst in lists:
    if element in lst:
        print(lst)

Upvotes: 1

rockzxm
rockzxm

Reputation: 352

It might help you:

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]
for lst in lists:
    if element in lst:
        print(lst)

Upvotes: 3

Related Questions