4

Given the list (listEx) in the following code, I am trying to separate the string and integer and float types, and put them all in their own respective lists. If I want to extract strings only from listEx list, the program should go through listEx, and put the strings in a new list called strList and then print it out to the user. Similarly for integer and float types as well. But if I can just figure out the correct way to do just one, I'll be fine for the others. So far no luck, been at this for an hour now.

listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55]
strList=['bcggg'] 

for i in listEx:
    if type(listEx) == str:
        strList = listEx[i]
        print strList[i]
    if i not in listEx:
        break
    else:
        print strList

for i in strList:
    if type(strList) == str:
        print "This consists of strings only"
    elif type(strList) != str:
        print "Something went wrong"
    else:
        print "Wow I suck"

5 Answers 5

3

Perhaps instead of if type(item) == ..., use item.__class__ to let the item tell you its class.

import collections
listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55]
oftype = collections.defaultdict(list)
for item in listEx:
    oftype[item.__class__].append(item)

for key, items in oftype.items():
    print(key.__name__, items)

yields

int [1, 2, 3, 55]
str ['moeez', 'string', 'another string']
float [2.0, 2.345]

So the three lists you are looking for can be accessed as oftype[int], oftype[float] and oftype[str].

Sign up to request clarification or add additional context in comments.

Comments

2
integers = filter(lambda x: isinstance(x,int), listEx)

strings = filter(lambda x: isinstance(x,str), listEx)

and so on...

Comments

2

Simply change type(strList) and type(listEx) to type(i). You are iterating over the list, but then checking whether or not the list is a string, not whether or not the item is a string.

Comments

1

Python for loops iterate over actual object references. You may be seeing strange behavior partly because you're giving the object reference i where a numerical list index should go ( the statement listEx[i] makes no sense. Array indices can be values of i = 0...length_of_list, but at one point i="moeez")

You're also replacing the whole list every time you find an item (strList = listEx[i]). You could instead add a new element to the end of the list using strList.append(i), but here's a more concise and slightly more pythonic alternative that creates the entire list in one line using a very useful python construct called list comprehensions.

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
[]

2 Comments

This works! Thank you so much. Now just one last thing. Can you just walk me through exactly what happens when the interpreter goes through "i for i in listEx if type(i) == str"? I kinda get it, but not completely.
I added a link to a simple tutorial page that describes the process- does that help? Essentially, this is a "for each" loop, in which you can iterate over the objects in the list directly (rather than using an array index as your loop variable). The official python documentation is actually quite good: docs.python.org/2/tutorial/controlflow.html#for-statements
-1
     python 3.2
     listEx = [1,2,3,'moeez',2.0,2.345,'string','another string', 55]

     strList = [ i for i in listEx if type(i) == str ] 
     ## this is list comprehension ##

     ###  but you can use conventional ways.

     strlist=[]                   ## create an empty list.          
     for i in listex:             ## to loop through the listex.
             if type(i)==str:     ## to know what type it is
                    strlist.append(i)        ## to add string element
     print(strlist)    



     or:
     strlist=[]
     for i in listex:
            if type(i)==str:
                strlist=strlist+[i]

     print(strlist)  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.