Search an Element from a list of Heterogeneous Data Types in Python

List in Python is a collection of heterogeneous data that means we can have different types of data elements inside any list. Though normal methods are available to find out any element from the same type of data available in a list.

Our problem is how to write a program so that I could search for any type of data available in a list. Let’s try to understand our problem first. Suppose this is our available list of elements that contain integers, float and string values.

list = [10,20,30,"a","abc", 50,56.78,'40']

Now you are required to read a value from the input and then find out what do you want to search in this a list.

value = input(“Enter anything that you want to search:”)

Simple erroneous solutions that most of the time our students implement is

list = [10,20,30,'a','abc',50,60.56,'40')
value = input("Enter any thing  :")
if value in list :
   print("found")
else:
   print("not found")

Can you guess what is wrong with this program?

The above program is designed to find out only “string” values inside this list so whenever you want to search 60.56, Your program will fail to produce the desired result, known as ‘logical error’.’

so you may be tempted to introduce Type Casting like this

value = int(input("Enter any thing :"))

and now you just modified your program to find out integer values from this list.  Now you are able to understand the problem, if you are going to typecast your program then it is going to find only that type of values.

So how to write a single program that automatically searches all type of information from this heterogeneous data. Here is the source code solution to this problem.

#   program to search an element from a list of different type of values
#   Developed by        : rakesh kumar
#   Last revised on     : 20-lujy-2019

list =[10,20,'a','abc',40,50.6]
a = input("Enter any number")
try:                # if we are able to type cast the value
    b  = eval(a)
    if b in list:
        print("found")
    else:
        print("not found")
except:             # if some run time error occur while conversion
    if a in list:
        print("Found")
    else:
        print("not  found")

We developed this script using try-except for method and used eval()function to find out the exact value entered by the user. If the eval() function is able to convert the entered number into its equivalent value then the program searches the value as integer, float or char otherwise it will jump on except part and search the same as “string”

Hope you have enjoyed this problem? If you know any such question? or have a better solution or any query. Please forward it via your comments.

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.