From 34c9342b213d052da9232b17fbc892b3d4e9f9b5 Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Tue, 4 Aug 2009 17:30:24 -0700 Subject: [PATCH] added section on tuples in a boolean context --- native-datatypes.html | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/native-datatypes.html b/native-datatypes.html index cb2903a..cad50e9 100755 --- a/native-datatypes.html +++ b/native-datatypes.html @@ -499,6 +499,29 @@ AttributeError: 'tuple' object has no attribute 'remove'

Tuples can be converted into lists, and vice-versa. The built-in tuple() function takes a list and returns a tuple with the same elements, and the list() function takes a tuple and returns a list. In effect, tuple() freezes a list, and list() thaws a tuple. +

Tuples In A Boolean Context

+ +

You can use tuples in a boolean context, such as an if statement. + +

+>>> def is_it_true(anything):
+...   if anything:
+...     print('yes, it's true')
+...   else:
+...     print('no, it's false')
+...
+>>> is_it_true(())             
+no, it's false
+>>> is_it_true(('a'))          
+yes, it's true
+>>> is_it_true((False))        
+yes, it's true
+
    +
  1. In a boolean context, an empty tuple is false. +
  2. Any tuple with at least one item is true. +
  3. Any tuple with at least one item is true. The value of the items is irrelevant. +
+

Assigning Multiple Values At Once

Here’s a cool programming shortcut: in Python, you can use a tuple to assign multiple values at once.