0

But i get one or more elements in list that not of type int

class CyberList:

    def __init__(self, new_list):
        for i in new_list:
            if type(i) != int:
                new_list.remove(i)
        print(new_list)

CyberList([1, 2, '', [], 2, 'ggt', 'gg'])

I try to use metods remove(), pop(), but it doesn't help List must include only int types

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Why not [`filter()`](https://docs.python.org/3/library/functions.html#filter)? – tadman Feb 07 '23 at 16:17
  • 5
    You shouldn't mutate a list while iterating over it. It will mess up the iteration index – mousetail Feb 07 '23 at 16:18
  • 1
    This is a common pitfall in python that folks run into often. Namely, removing items from a list inside of a for loop, and the unexpected results of that operation. Check out [this very popular question](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) about how to remove items from a list while iterating, properly. – JNevill Feb 07 '23 at 16:18
  • Don't use `type()` use `isinstance(i, int)` – roganjosh Feb 07 '23 at 16:21
  • 2
    @JNevill Not just Python. It's common in every programming language with mutable collections, which includes virtually all mainstream programming languages. – Konrad Rudolph Feb 07 '23 at 16:23
  • Create a new list: `new_list=[x for x in [1, 2, '', [], 2, 'ggt', 'gg'] if type(x).__name__=='int']` if you specifically only want `int` or `new_list=[x for x in [1, 2, '', [], 2, 'ggt', 'gg'] if isinstance(x, int)]` if derivatives are OK. – dawg Feb 07 '23 at 16:26
  • @KonradRudolph for sure. This is a common problem even with folks iterating through rows in excel in VBA and deleting as they go. I think that question comes daily in the VBA tag for folks with the intestinal fortitude to follow that circus of a tag. – JNevill Feb 07 '23 at 16:46

0 Answers0