[Python] Let's master all and any

Introduction

atcoder tutorial There was a problematic one that had to determine whether each element of the list was even or odd, so I usually had a built-in function when I thought it would be easy to write. It may be a story to write that much, but please let me use it because it is prepared.

all(iterable)

Returns True if all ** elements of iterable are true ** (or if iterable is empty).

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

Here's what ** itarable ** is.

What is iterable?

A repeatable object. An object that returns one element at a time.     ex) Lists, tuples, dictionaries ...

Passing this as an argument to ** iter () ** will return ** iterator ** for the object. (** iterator ** is an object that expresses the flow of data (roughly))

For example

for i in A:

A here is ** itarable **. for automatically calls ** iter () ** to create a temporary anonymous variable and keep the ** iterator ** while looping.

So let's try ʻall`!

The following is a program that checks if all the elements of the array ** array ** using ʻall` are int type. Think about what it looks like before you look at the output!

def check(array):
  if all( isinstance(x, int) for x in array):
    print("Array{}All elements of are int type".format(array))
  else:
    print("Array{}Some of the elements are not int type! !!".format(array))


check([2,5,6]) 
check([1,4,[]])
check(["1",2,3])
check([])
check(1)
Output result

All elements of array [2, 5, 6] are int type Some elements of the array [1, 4, []] are not of type int! !! Some elements of the array ['1', 2, 3] are not of type int! !! All elements of array [] are int type

TypeError Traceback (most recent call last)
Omitted
TypeError: 'int' object is not iterable

Was it as expected? ** True ** is also returned for empty arrays. Well, of course, I got an error saying that the fifth one is not iterable. Keep these points in mind.

any(iterable) Next, I will write about ʻany ()`. It's a little late, but there seems to be no demand for explanation because the contents of these two functions are still the function names (laughs).

Returns True if any ** element of iterable is true **. Returns False if iterable is empty. Equivalent to the following code:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

The following is a program that checks if an element of an array ** array ** using ʻany` has an int type. As before, think about what it will look like before you look at the output!

def check(array):
  if any( isinstance(x, int) for x in array):
    print("Array{}There is an int type in the element of! !!".format(array))
  else:
    print("Array{}There is no int type in the element of!".format(array))


check([2,"5","6"]) 
check(["1","4","a"])
check([])
check([1])

Output result

The element of the array [2, '5', '6'] has an int type! !! There is no int type in the element of the array ['1', '4','a']! There is no int type in the element of array []! Int type is in the element of array [1]! !!

how was it? No. 3 is especially careful. You can see that False is returned in the case of an empty array, unlike ʻall`. Well, is there anything else I can explain?

in conclusion

What did you think? I can't deny the commentary and the feeling that there was no demand in the first place, but I hope it helps. Then this time around here!

Recommended Posts

[Python] Let's master all and any
[Blender x Python] Let's master random !!
[Blender x Python] Let's master rotation !!
[Blender x Python] Let's master the material !!
[python] Check the elements of the list all, any
Let's control EV3 motors and sensors with Python
Python functions ~ max, min, sum, len, all, any
Let's write a Python program and run it
What are python tuples and * args after all?
[python] Compress and decompress
Python and numpy tips
[Python] pip and wheel
Batch design and python
Python iterators and generators
Let's write python code that parses go code and generates go code
Python packages and modules
Vue-Cli and Python integration
Python string manipulation master
Ruby, Python and map
Let's make a simple game with Python 3 and iPhone
python input and output
Python and Ruby split
About __all__ in python
Python3, venv and Ansible
Python asyncio and ContextVar
Let's review the language specifications around Python iterators and generators
Let's create a PRML diagram with Python, Numpy and matplotlib.
[Python beginner] How do I develop and execute Python after all?
[2020 version] Let Python do all the tax and take-home calculations
[Let's play with Python] Image processing to monochrome and dots
Aim python library master (48) autopep8
Aim python library master (36) json2html
Aim python library master (49) psidialogs
Let's use def in python
Let's use python janome easily
Programming with Python and Tkinter
Aim python library master (26) easyxml
Encryption and decryption with Python
Aim python library master (29) table_printer
Aim python library master (55) namespaces
Aim python library master (46) browserplus
Python: Class and instance variables
3-3, Python strings and character codes
Python 2 series and 3 series (Anaconda edition)
Aim python library master (30) chronyk
Python on Ruby and angry Ruby on Python
Python indentation and string format
Aim python library master (3) workalendar
Python real division (/) and integer division (//)
Aim python library master (37) slimurl
Install Python and Flask (Windows 10)
Aim python library master (44) pynetviz
Aim python library master (8) rolex
Aim python library master (52) marktime
Aim python library master (7) numparser
About python objects and classes
About Python variables and objects
Let's run Excel with Python
Aim python library master (21) hy
Aim python library master (18) requests
Apache mod_auth_tkt and Python AuthTkt