Satvik
Satvik

Reputation: 137

How to Check multiple coma separated string present in list or not

I'm trying to search coma separated string present in list or not, like multiple string present in list or not. How to perform this operation

I tried like this

location = ["Bangalore", "Delhi"]
locations_list = ["Bangalore", "Delhi", "Mumbai", "Hyderabad", "Uttar Pradesh"]

if any(location in str for str in locations_list ):
    print("location present in locations list")
else:
    print("location not found")

Upvotes: 0

Views: 88

Answers (3)

bexi
bexi

Reputation: 1216

If you're only interested in whether or not any of the elements is present, I would suggest doing it using set intersections:

if set(location) & set(locations_list):
    print("location present in locations list")
else:
    print("location not found")

EDIT:

In case you want to check if all locations in location are in location_list, I suggest using the set's issubset method:

if set(location).issubset(set(locations_list)):
    print("location present in locations list")
else:
    print("location not found")

Upvotes: 4

Jesus Prieto
Jesus Prieto

Reputation: 11

Here I give you a correct example of implementation.

location = ["Bangalore", "Delhi"]
locations_list = ["Bangalore", "Delhi", "Mumbai", "Hyderabad", "Uttar Pradesh"]
for location in location :
    for ref in locations_list:
        if location == ref:
            print(f"{location} present in locations list")

This is a classic aproximation of your task. However as you know nested loops are horrible in performance.

So... I give you this a little better implementation:

    location = ["Bangalore", "Delhi"]
locations_list = ["Bangalore", "Delhi", "Mumbai", "Hyderabad", "Uttar Pradesh"]
[print(f"{location} present in locations list") for location in location for ref in locations_list if (location == ref)]

In this code I've used list comprehension to improve a little the performance,but the concept is the same. Check every item in the first list and compare it to every item in the other list.

Maybe you could improve your performance adding a continue everytime you get a match.

I know these aren't the best way to perform that kind of search, but both of them are simple and runnable.

PD: Just to mark, I've used python 3.6+ if you want to run the codes in lower versions just remove the f before strings

Upvotes: 1

Sociopath
Sociopath

Reputation: 13426

In your code you are checking if list is in str rather than if str is in list.

Change your code as below:

if any(lcr in location for lcr in locations_list ):
    print("location present in locations list")
else:
    print("location not found")

Upvotes: 1

Related Questions