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?
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]
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)]
you can use isinstance(item, int)
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.