2

First of all, complete python/programming newbie here, so I apologise if this is a stupid question. Also, sorry for the awkward title.

I'm attempting to adapt the top answer in this question: Check if a Python list item contains a string inside another string. However, I'm not sure if what I'm trying to achieve is even possible.

list6 = [list1,list2,list3,list4,list5]

'list6' is a list containing several other lists. Then, this line can be used to check if 'Cool' is a string inside of any of those lists:

if any("Cool" in s for s in list6):

My question is: Assuming 'Cool' is only in 'list1', is it possible to fetch and store 'list1' in order to use other values within that list? For example:

if "Cool" is in any list in list6:
    list = list with "Cool"
    something = list[4]
Squito
  • 23
  • 2
  • you would have to use `for`-loop to check every sublist separatelly and then you can keep it and get other elements from this sublist. – furas Feb 06 '20 at 21:52

2 Answers2

3

You can use next with a generator expression (Thanks ShadowRanger)

next(sublist for sublist in list6 if "Cool" in sublist)

or you can use next with an iterator such as filter to get the first item that contains the element

next(filter(lambda x: "Cool" in x, list6))
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • 2
    Slightly nicer than `filter`+`lambda` is a simple genexpr: `next(sublist for sublist in list6 if "Cool" in sublist)`. – ShadowRanger Feb 06 '20 at 21:57
  • 1
    @ShadowRanger - Thanks! I was trying to use just next but been awake for far too long today it seems – Sayse Feb 06 '20 at 21:59
0

You would have to use for-loop to check every sublist separatelly and then you can keep it or get other elements from this sublist.

for sublist in list6:
    if "Cool" in sublist:
        something = sublist[4]
furas
  • 134,197
  • 12
  • 106
  • 148
  • Note: Add a `break` inside the `if` unless you want to keep looking after you've already got a hit to get the last hit (and if you did want to keep the last hit, you'd be better off looping over `reversed(list6)` and still `break`ing when you get a hit). – ShadowRanger Feb 06 '20 at 21:58