Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a tuple of an empty tuple in Python?

Tags:

python

tuples

How can I create a tuple consisting of just an empty tuple, i.e. (())? I have tried tuple(tuple()), tuple(tuple(tuple())), tuple([]) and tuple(tuple([])) which all gave me ().

The reason that I use such a thing is as follows: Assume you have n bags with m items. To represent a list of items in a bag, I use a tuple of length n where each element of that tuple is a representative for a bag. A bag might be empty, which is labeled by (). Now, at some initial point, I have just one bag with empty items!

like image 351
Ali Shakiba Avatar asked Jun 18 '16 09:06

Ali Shakiba


People also ask

How do I add an empty tuple?

You can't add a tuple and number. Your line should probably be newtup += (aTup[i],) . Haven't checked it though. Adding the parentheses and comma turns the number into a tuple with a single member.

What is empty tuple in Python?

You can create empty tuple object by giving no elements in parentheses in assignment statement. Empty tuple object is also created by tuple() built-in function without any arguments >>> T1 = () >>> T1 () >>> T1 = tuple() >>> T1 () Pythonic. © Copyright 2022. All Rights Reserved.

How do I make an empty tuple list in Python?

To create an empty tuple, use empty parenthesis or the tuple() function. Using empty parenthesis is faster and usually more efficient compared to using the tuple() function. It is also considered more pythonic and the recommended way of creating empty tuples.

What is the size of an empty tuple in Python?

Explanation: An Empty Tuple has 48 Bytes as Overhead size and each additional element requires 8 Bytes.


2 Answers

The empty tuple is () (or the more-verbose and slower tuple()), and a tuple with just one item (such as the integer 1), called a singleton (see here and here) is (1,). Therefore, the tuple containing only the empty tuple is

((),) 

Here are some results showing that works:

>>> a=((),) >>> type(a) <type 'tuple'> >>> len(a) 1 >>> a[0] () >>> type(a[0]) <type 'tuple'> >>> len(a[0]) 0 
like image 180
Rory Daulton Avatar answered Sep 25 '22 06:09

Rory Daulton


I'm not surprised this (()) didn't work, since the outer parentheses get interpreted as that - parentheses. So (()) == (), just like (2) == 2. This should work, however:

((),) 
like image 45
juanpa.arrivillaga Avatar answered Sep 23 '22 06:09

juanpa.arrivillaga