Site icon

Finding an Item in Python List

Solution: Method 1

# List 
num = [1, 2, 3, 4, 5, 13]
num1 = [1, 2, 3, 4, 5]

# Function to find
def find_item(lst, itm):     
        for ii in lst:
            if ii==itm:
                flag = 1
            else:
                flag=0
	
        if flag==1:
            print(f'Yes! {itm} is in the List')
        else: 
            print(f'No! {itm} is NOT in the List')
        
        
find_item(num, 13) # O/p -> Yes! 13 is in the List
find_item(num1, 13) # O/p -> No! 13 is NOT in the List
    

Solution: Method 2

# List 
num = [1, 2, 3, 4, 5, 13]
num1 = [1, 2, 3, 4, 5]

# Function to find
def find_item(lst, itm):
    if itm in lst:
        print(f'Yes! {itm} is in the List')
    else:
         print(f'No! {itm} is NOT in the List')
    
find_item(num, 13)
find_item(num1, 13)

Spread the love
Exit mobile version