1

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.

3
  • 2
    use for item in lst: instead of for n in range(len(lst)): and lst[n] Commented Sep 16, 2022 at 23:15
  • You can simplify the inner loop to if element in lst, but otherwise no choice but to loop... Commented Sep 16, 2022 at 23:16
  • I answered, let me know if that helped! I used a function. Commented Sep 16, 2022 at 23:24

5 Answers 5

3

It might help you:

lists = [['A', 'B', 'D', 'E', 'F', 'G', 'H'], ['C']]
for lst in lists:
    if element in lst:
        print(lst)
Sign up to request clarification or add additional context in comments.

Comments

2

You can try this:

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

Comments

0

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

Comments

0

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.