User
User

Reputation: 826

Get an element by a substring of its value in python list

I have a list like this content = ['C:\User\Folder\a.txt', 'C:\User\Folder\big_a.txt', 'C:\User\Folder\small_a.txt'] in which every item is unique, I can't have for example two C:\User\Folder\small_a.txts, of course.
Now I want to get the item that matches the string big.
What I'm doing is

for file in content:
    if 'big' in file:
        path = file
        break

And it works.

What I ask you is: there's a different way to do that? Maybe more efficient or something in one line?
Just curiosity

Upvotes: 3

Views: 136

Answers (3)

felipe
felipe

Reputation: 8025

You could use a list comprehension to do the same task in fewer lines, but it will not be the most optimal since it will not contain the break statement. Regardless of whichever way you chose to do (list-comprehension vs for) this will be an O(n) operation.

content = ["a.txt", "big_a.txt", "small_a.txt"]
file = next(i for i in content if "big" in i)

print(file) #> big_a.txt

Upvotes: 1

amitgcse
amitgcse

Reputation: 31

I am not sure about efficiency, but this is definitely beautiful to read and write

path = [file for file in  content if 'big' in file]

Upvotes: 1

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

This basically does the same of your code:

path = next(file for file in content if "big" in file)

Upvotes: 4

Related Questions