Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple declaration in Python

In python, one can declare a tuple explicitly with parenthesis as such:

>>> x = (0.25, 0.25, 0.25, 0.25)
>>> x
(0.25, 0.25, 0.25, 0.25)
>>> type(x)
<type 'tuple'>

Alternatively, without parenthesis, python automatically packs its into a immutable tuple:

>>> x = 0.25, 0.25, 0.25, 0.25
>>> x
(0.25, 0.25, 0.25, 0.25)
>>> type(x)
<type 'tuple'>

Is there a pythonic style to declare a tuple? If so, please also reference the relevant PEP or link.

There's no difference in the "end-product" of achieving the tuple but is there a difference in how the tuple with and without parenthesis are initialized (in CPython)?

like image 301
alvas Avatar asked Jan 15 '16 10:01

alvas


People also ask

How do you declare a tuple?

Creating a Tuple In Python, tuples are created by placing a sequence of values separated by 'comma' with or without the use of parentheses for grouping the data sequence. Note: Creation of Python tuple without the use of parentheses is known as Tuple Packing.

How is tuple declared in Python?

A tuple is created by placing all the items (elements) inside parentheses () , separated by commas. The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

What is tuple in Python example?

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable.

What is a 3 tuple in Python?

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets.


1 Answers

From practical point of view it's best to always use parenthesis as it contributes to readability of your code. As one of the import this moto says:

"Explicit is better then implicit."

Also remember, that when defining one-tuple you need a comma: one_tuple = (15, ).

like image 193
Nikita Avatar answered Sep 29 '22 07:09

Nikita