Python for loops iterates over actual object references. You can observe strange behavior partly because you give a reference to object i, where the index of the number list should be indicated (the listEx[i] operator does not make sense. Array indices can be values i = 0 ... length_of_list, but for one point I = "moeez")
You also replace the entire list every time you find an element ( strList = listEx[i] ). Instead, you can add a new element to the end of the list using strList.append(i) , but here's a shorter and slightly simpler option, which creates the entire list on one line using a very useful python construct called list .
listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55] strList = [ i for i in listEx if type(i) == str ]
gives:
print strList >>> print strList ['moeez', 'string', 'another string']
For the rest
>>> floatList = [ i for i in listEx if type(i) == float ] >>> print floatList [2.0, 2.345] >>> intList = [ i for i in listEx if type(i) == int ] >>> intList [1, 2, 3, 55] >>> remainders = [ i for i in listEx if ( ( i not in strList ) and (i not in floatList ) and ( i not in intList) ) ] >>> remainders []
source share