-3

Tried to implement List comprehension in Python 3.7x with following example

a_list = [1, ‘4’, 9, ‘a’, 0, 4]
squared_ints = [ e**2 for e in a_list if type(e) == types.IntType ]  

However it fails with the below error

NameError: name 'types' is not defined

Can anyone help me on this ?

001
  • 13,291
  • 5
  • 35
  • 66

3 Answers3

3

First off, the NameError is because you need to import the types module before you can use it:

import types 

However, this still won't work since types.IntType doesn't exist in Python 3; int is already available as a built-in so it's unnecessary.

Finally, you generally shouldn't do type comparisons using equality; prefer isinstance checks instead:

a_list = [1, '4', 9, 'a', 0, 4]
squared_ints = [ e**2 for e in a_list if isinstance(e, int)]  
tzaman
  • 46,925
  • 11
  • 90
  • 115
0

Since it says, types is not defined, you better search for what class you are referencing to.

While, on the other hand, a different way to do this is:

a_list = [1, ‘4’, 9, ‘a’, 0, 4]
squared_ints = [ e**2 for e in a_list if type(e) == int ]  

Hope it helps.

Sarques
  • 465
  • 7
  • 17
-1

Instead of types.IntType, you can try type(e) == int

squared_ints = [ e**2 for e in a_list if type(e) == int ] 

For built-in data types you can call them as-is (ie, int, str, dict, list, tuple, set etc)

PlopMon
  • 16
  • 5