2

For example: I have a list called container. In it are some elements and I want to check if eg. any of them are complex.

container = [1, 0.5, "text", 1j]    
if isinstance(container[?], complex):
    print("This list has complex elements")

In this example, I could've written container[-1], but is there an universal method? I could use a for loop, but I'm wondering if there are better ways to do this.

mteXD
  • 33
  • 5

3 Answers3

6

There are many ways to apply something to entire container, e.g.

any(isinstance(element, complex) for element in container)
lejlot
  • 64,777
  • 8
  • 131
  • 164
2

You could use a list comprehension along with python's any() function:

any([isinstance(x, complex) for x in container])

This would return True if the list has complex numbers.

Ilia
  • 111
  • 6
  • 2
    This is practically the same solution as [lejlot's answer](/a/70229110/4518341), though it'll be slower if `container` is very large, since `any` can't short-circuit a list [like it can a generator](/a/17246413/4518341). – wjandrea Dec 04 '21 at 20:19
0

With pure python I think you would have to explicitly iterate over the list. It can be done with a simple list comprehension:

if any([isinstance(c, complex) for c in container]):
    print("List has complex elements")
defladamouse
  • 567
  • 2
  • 13
  • 2
    This is practically the same solution as [lejlot's answer](/a/70229110/4518341), though it'll be slower if `container` is very large, since `any` can't short-circuit a list [like it can a generator](/a/17246413/4518341). – wjandrea Dec 04 '21 at 20:19
  • Thanks @wjandrea, I never think of using generators for some reason, that answer is definitely better. – defladamouse Dec 04 '21 at 20:36