fluffyyboii
fluffyyboii

Reputation: 645

Is there a way to find if an item in a nested list exists?

I was wondering if there was a way to do something like this is Python. Any ideas?

inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = [inches, centimeters]
unit = input("Enter unit here... ")
if unit not in allUnits:
    print("Invalid unit!")

Upvotes: 0

Views: 80

Answers (4)

brebiv
brebiv

Reputation: 11

If you really need to use array of arrays you can do like that. Inspired by C++.

def isInArray(array, unit):
    for i in range(len(array)):
        for j in array[i]:
            if j == unit:
                return True;
    return False

unit = input("Enter unit here... ")
if not isInArray(allUnits, unit):
    print("Invalid unit!")

Upvotes: 0

rdas
rdas

Reputation: 21285

You're close:

inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = [*inches, *centimeters] # notice the `*`
unit = input("Enter unit here... ")
if unit.lower() not in allUnits:
    print("Invalid unit!")

Should do the trick.

The * operator unwinds the lists into their constituent elements. Which can then be used to create a new list. So you can flatten the two lists into one that way.

I also added unit.lower() to make the string comparison case-independent.

Upvotes: 2

Luke-zhang-04
Luke-zhang-04

Reputation: 793

if unit not in inches + centimeters:
    print("Invalid unit!")

Upvotes: 1

Paweł Kowalski
Paweł Kowalski

Reputation: 544

Just add lists:

inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = inches + centimeters
unit = input("Enter unit here... ")
if unit not in allUnits:
    print("Invalid unit!")

Upvotes: 1

Related Questions