So I was given a list and I must print the type of each item in the list. I can clearly see that there are strings and integers but I need it to print out in Python. We just
a=[12,"string"]
for i in a: #sets the value of a to be any item in list (a)
print(type(a), end=" ")
OUTPUT:
>>> <type 'int'> <type 'str'>
In the python code above type() function is used to determine the data type of variable (i). And end() is used to replace the end of the output with the value inside its' brackets () instead of a new line as you must have observed in the above output that between the 2 outputs "____ " (space) was placed without a new line.
Here is how I would do it using type().
myList = [1,1.0,"moo"] #init the array
for i in myList:
print(type(i)) #loop and print the type
use the type
built in function of python.
lst = ['string', 1, 2, 'another string']
for element in lst:
print type(element)
output:
<type 'str'>
<type 'int'>
<type 'int'>
<type 'str'>
foo = [1, 0.2, "bar"]
for i in foo:
print(type(i))
Should print out the type of each item
ls = [type(item) for item in list_of_items]
print(ls)
Essentially, the type function takes an object and returns the type of it. Try the below code:
for item in [1,2,3, 'string', None]:
print type(item)
Output:
<type 'int'>
<type 'int'>
<type 'int'>
<type 'str'>
<type 'NoneType'>