简体   繁体   中英

Python tuples: How can i have only one element as pair?

Output from interpreter:

>>> (1)
1
>>> (1,)
(1,)

The question is what is the difference?

It seems that (1) means (1)+0=...

That's the definition of tuple. I cannot have a tuple with 1 data-element?

Edit: Same output from:

>>> tuple([1])
(1,)
>>> 

You can have a one-element tuple, you just need the trailing , like in your second example.

Parenthesis without , mean whatever inside is just a normal expression and can sometimes be used to split a long expression into several lines: How can I do a line break (line continuation) in Python?

When you use a comma in your tuple, you're telling it that it's a tuple. A tuple with 1 element and without the comma is just a number, grouped by parenthesis, as you would see in arithmetic.

tuples in python defined by the, not the parentheses because of that when you are doing (1) python interoperate that it's int so if you are doing (1,) it's the same as 1, and then python interoperates it to tuple.
this is the definition of tuples in python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM