-1

Just like the title but how do I check if a certain element is an integer and square those in list while deleting elements that aren't integer?

For example, the list is [0, 2, 'Python', 'C++', 3]

And this is what I tried:

def main():
    lst = [0, 2, 'Python', 'C++', 3]

    print("Given list: ", lst)
    newLst = [item**2 for item in lst if type(lst[item]) == int]

    print("The list which only contains square of integers: ", newLst)

main()

And error happens;

TypeError: list indices must be integers or slices, not str

What am I missing?

AMC
  • 2,642
  • 7
  • 13
  • 35
  • 1
    You should really use `isinstance` instead of `type`: `if isinstance(item, int)` – DeepSpace May 01 '20 at 19:52
  • _What am I missing?_ Look at the error message, and look at the comparison you're trying to do ;) Please provide the entire error output. As an aside, variable and function names should generally follow the `lower_case_with_underscores` style. – AMC May 01 '20 at 22:02

4 Answers4

1

The problem in your code is that you are using the element item in order to slice a list - but indices must be integers. Therefore, you should change

newLst = [item**2 for item in lst if type(lst[item]) == int]

to

newLst = [item**2 for item in lst if type(item) == int]

Alternatively, you can use isinstance() in order to test if the element is of type int:

lst = [0, 2, 'Python', 'C++', 3]
lst_num = [ x**2 for x in lst if isinstance(x, int)]

and the output will be:

print(lst_num)
[0, 4, 9]
Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
1

item is the list element, not its index. You should use type(item), not type(lst[item])

newLst = [item**2 for item in lst if type(item) == int]

It's also preferable to use isinstance() because it works with subclasses.

newLst = [item**2 for item in lst if isinstance(item, int)]
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Upvoted for explaining where the OP made the mistake to help them learn, also for incorporating DeepSpace's comment. – Simon Notley May 01 '20 at 19:55
  • Wow. I feel really dumb right now. Thank you for your answer! I am really new to Python so I don't know much but I will keep trying to become better! – user116236 May 02 '20 at 00:04
0

you can use isinstance(item, int)

0

The canonical way to do a typecheck in Python is isinstance(val,int) instead of type(val) == int as was answered in this previous post What's the canonical way to check for type in Python?

Kim Mens
  • 325
  • 1
  • 13