atlantis.pd
atlantis.pd

Reputation: 68

Why does python all() function return true for a tuple?

I know that the built-in all() function returns true when all elements of the iterable are true. But when I create a tuple and give it 2 random integers as elements, it returns true. Why is that?

For example:

tup = 1234 , 5678

and call the all() function on it:

print ( all(t) ) 
>>> True 

I'm confused because I thought python could only return true or false when a boolean operation has been performed.

But I haven't performed a boolean operation, I only gave all() 2 integers. I didn't say for example 2>= 1. So why does all() return true for my tuple? Or is that just the default answer?

Upvotes: 0

Views: 2406

Answers (3)

Bishwas Mishra
Bishwas Mishra

Reputation: 1342

The assumption, "Python could only return true or false when a boolean operation has been performed" is not correct.

The objects defined in Python library:None, False, 0, 0L, 0.0, 0j, '', (), [], {} are considered False. Any other values (or objects, even classes and functions) are considered True. Read: Truth Value Testing

Therefore, both of the followings are True:

tup = 1234 , 5678
if(tup):
    print 'True'
>> True

def a_func():
    print 'This is a function'
if(a_func):
    print 'True'
>> True

all(single_parameter_iterator) is a method in Python which returns true if all the values of the iterator passed to it is True. Read: all() method in Python

What is an iterator?

  • We use for statement for looping over a list.
  • If we use it with a string, it loops over its characters.
  • If we use it with a dictionary, it loops over its keys.
  • If we use it with a file, it loops over lines of the file.

Source: Iterators in Python

You already gave the answer yourself:

"I know that the built in function all () returns true when all elements of the iterable are true."

Upvotes: 1

agasthya_tadakamalla
agasthya_tadakamalla

Reputation: 114

1.def all(iterable):
2.    for element in iterable:
3.        if not element:
4.            return False
5.    return True

This is the definition of built-in all function in python . not element in the 3rd line must be returning false in your case.

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336428

Any non-zero number or non-empty sequence evaluates to True.

In [1]: bool(123)
Out[1]: True

In [2]: bool(0)
Out[2]: False

In [3]: bool("0")
Out[3]: True

In [4]: bool("")
Out[4]: False

In [5]: bool([0])
Out[5]: True

In [6]: bool([])
Out[6]: False

etc. This allows you to write elegant, concise statements like

if score:

instead of

if score != 0:

or

if sequence:

instead of

if len(sequence) > 0:

Upvotes: 5

Related Questions