I am trying to create a function which would take a list and be able to count the number of ints floats and str in that list.

output should be:

list =
freq = countDataTypes(list)
print(freq)

[2,1,1]


any help would be greatly appreciated


so far:

>>> def countDataTypes(aList):
	rtnlist = [0,0,0]
	for x in aList:
		if type(x) is string:

the rtnlist[0,0,0] is what this will return. if there are 2 ints, 1 float and 0 str then rtnlist[2,1,0]

I suggest using a dictionary. Using name "seq" instead for "list" avoids masking built-in function list().

>>> seq = ['v', 3.0,1, 'etc']
>>> dd = {}
>>> for item in seq:
... 	v = dd.get(type(item), 0)
... 	dd[type(item)] = v+1
... 	
>>> [dd[obj] for obj in (int, float, str)]
[1, 1, 2]
>>>

Thanks for the help but I am a beginner and am supposed to use a for and if-else construct in the solution, which is what I tried to do in the original post. I do not understand line 7 of the solution since I am not an advanced programmer

My main issue is using if-else to identify type of list element and for loop to add to the rtnlst[0,0,0]

I suggest using a dictionary. Using name "seq" instead for "list" avoids masking built-in function list().

>>> seq = ['v', 3.0,1, 'etc']
>>> dd = {}
>>> for item in seq:
... 	v = dd.get(type(item), 0)
... 	dd[type(item)] = v+1
... 	
>>> [dd[obj] for obj in (int, float, str)]
[1, 1, 2]
>>>

Edited 4 Years Ago by unigrad101: n/a

def count_data_types(a_list):
    answer = [0,0,0]
    for x in a_list:
        for ind, t in enumerate((int, float, str)):
            if t == type(x):
                answer[ind] += 1
    return answer

print(count_data_types(['v', 3.0,1, 'etc']))

I am not sure what the for loop with the ENUMERATE function is. is there another way to do this?

def count_data_types(a_list):
    answer = [0,0,0]
    for x in a_list:
        for ind, t in enumerate((int, float, str)):
            if t == type(x):
                answer[ind] += 1
    return answer

print(count_data_types(['v', 3.0,1, 'etc']))

Before enumerate() came around, you would have incremented the index this way:

def count_data_types(a_list):
    answer = [0,0,0]
    for x in a_list:
        ind = 0
        for t in (int, float, str):
            if t == type(x):
                answer[ind] += 1
            ind += 1
    return answer

print(count_data_types(['v', 3.0,1, 'etc']))


'''
[1, 1, 2]
'''
This question has already been answered. Start a new discussion instead.