-1

Here's the info: I have a list like this

trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','-3.7','Python']

Looking to create three lists - integer, string and float
Integer list will have: 9,0,-5,1,-600,4
Float list will have: 0.7,5.9
String list will have: Europe,-9,English,0,-2,-3.7,Python

Wrote this program. Output was integers and integers marked as string. Not kind of what I want. Tweaked it to do the same with float. Did not work. Looking for a better way to get the desired output. Thanks!

trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
newlistint=[]
newlistonlyint=[]
print(f'Initial list : {trylist}')
for item in trylist:
    try:
        int_val = int(item)
        print(int_val)
    except ValueError:
        pass
    else:
        newlistint.append(item) #will print only integers including numbers mentioned as string and digit of float
        print(f'newlistint is : {newlistint}')
        newlistonlyint.append(int_val)
        print(f'newlistonlyint is :{newlistonlyint}')
Aven Desta
  • 2,114
  • 12
  • 27
Ricky101
  • 5
  • 4

2 Answers2

0

int() tries to convert its argument to an int, raising a ValueError if this can’t be done. While it’s true that any integer argument to int() will not raise a ValueError, non-integer arguments like ‘9’ can be successfully converted to an integer (the integer 9 in this case), therefore not raising a ValueError.

Hence, trying to verify whether something is an integer by calling int() on it and catching ValueErrors just doesn’t work.

You should really be using the isinstance() function. Specifically, item is an int if and only if isinstance(item, int) returns True. Similarly, you can check for strings or floats by replacing int by str or float.

Baran Karakus
  • 193
  • 1
  • 7
0
trylist = [9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
int_list = [x for x in trylist if type(x)==int]
float_list = [x for x in trylist if type(x)==float]
str_list = [x for x in trylist if type(x)==str]

You can read about list comprehension here

Aven Desta
  • 2,114
  • 12
  • 27