Why does adding a trailing comma after an expression create a tuple with the expression's value? E.g. in this code:
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
Why is the printed output ('mystring',), and not just mystring?
It is the commas, not the parentheses, which are significant. The Python tutorial says:
A tuple consists of a number of values separated by commas
Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.
See the Python Tutorial section on Tuples and Sequences
Because this is the only way to write a tuple literal with one element. For list literals, the necessary brackets make the syntax unique, but because parantheses can also denote grouping, enclosing an expression in parentheses doesn't turn it into a tuple: you need a different syntactic element, in this case the comma.
Make sure to read this great answer by Ben James.
Tuples are not indicated by the parentheses. Any expression can be enclosed in parentheses, this is nothing special to tuples. It just happens that it is almost always necessary to use parentheses because it would otherwise be ambiguous, which is why the __str__ and __repr__ methods on a tuple will show them.
For instance:
abc = ('my', 'string')
abc = 'my', 'string'
What about single element tuples?
abc = ('mystring',)
abc = 'mystring',
So in effect what you were doing was to create a single element tuple as opposed to a string.
The documentation clearly says:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
Unpacking multi-element tuple:
a, b = (12, 14)
print(type(a))
Output:
int
Unpacking single-element tuple:
a, = (12, )
print(type(a))
Output:
int
Otherwise:
a = (12,)
print(type(a))
Output:
tuple
In the question's example, you assigned the variable 'abc' to a Tuple with a length of 1.
You can do multiple assignments with this similar syntax:
x,y = 20,50
Also note that the print statement has a special understanding for ending a print statement with a comma; This tells print to omit the trailing newline.
print 'hello',
print 'world'
result:
hello world
I was somewhat confused about the application of the comma, as you also apply a comma to make a list instead of tuple, but with a different variable assignment.
Hereby, a simple example that I made of how to create a tuple or a list.
abc = 1,2,3 # prints a tuple: (1, 2, 3)
*abc, = 1,2,3 # prints a list: [1, 2, 3]
Related
Why does adding a trailing comma after an expression create a tuple with the expression's value? E.g. in this code:
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
Why is the printed output ('mystring',), and not just mystring?
It is the commas, not the parentheses, which are significant. The Python tutorial says:
A tuple consists of a number of values separated by commas
Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.
See the Python Tutorial section on Tuples and Sequences
Because this is the only way to write a tuple literal with one element. For list literals, the necessary brackets make the syntax unique, but because parantheses can also denote grouping, enclosing an expression in parentheses doesn't turn it into a tuple: you need a different syntactic element, in this case the comma.
Make sure to read this great answer by Ben James.
Tuples are not indicated by the parentheses. Any expression can be enclosed in parentheses, this is nothing special to tuples. It just happens that it is almost always necessary to use parentheses because it would otherwise be ambiguous, which is why the __str__ and __repr__ methods on a tuple will show them.
For instance:
abc = ('my', 'string')
abc = 'my', 'string'
What about single element tuples?
abc = ('mystring',)
abc = 'mystring',
So in effect what you were doing was to create a single element tuple as opposed to a string.
The documentation clearly says:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
Unpacking multi-element tuple:
a, b = (12, 14)
print(type(a))
Output:
int
Unpacking single-element tuple:
a, = (12, )
print(type(a))
Output:
int
Otherwise:
a = (12,)
print(type(a))
Output:
tuple
In the question's example, you assigned the variable 'abc' to a Tuple with a length of 1.
You can do multiple assignments with this similar syntax:
x,y = 20,50
Also note that the print statement has a special understanding for ending a print statement with a comma; This tells print to omit the trailing newline.
print 'hello',
print 'world'
result:
hello world
I was somewhat confused about the application of the comma, as you also apply a comma to make a list instead of tuple, but with a different variable assignment.
Hereby, a simple example that I made of how to create a tuple or a list.
abc = 1,2,3 # prints a tuple: (1, 2, 3)
*abc, = 1,2,3 # prints a list: [1, 2, 3]
Why does adding a trailing comma after an expression create a tuple with the expression's value? E.g. in this code:
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
Why is the printed output ('mystring',), and not just mystring?
It is the commas, not the parentheses, which are significant. The Python tutorial says:
A tuple consists of a number of values separated by commas
Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.
See the Python Tutorial section on Tuples and Sequences
Because this is the only way to write a tuple literal with one element. For list literals, the necessary brackets make the syntax unique, but because parantheses can also denote grouping, enclosing an expression in parentheses doesn't turn it into a tuple: you need a different syntactic element, in this case the comma.
Make sure to read this great answer by Ben James.
Tuples are not indicated by the parentheses. Any expression can be enclosed in parentheses, this is nothing special to tuples. It just happens that it is almost always necessary to use parentheses because it would otherwise be ambiguous, which is why the __str__ and __repr__ methods on a tuple will show them.
For instance:
abc = ('my', 'string')
abc = 'my', 'string'
What about single element tuples?
abc = ('mystring',)
abc = 'mystring',
So in effect what you were doing was to create a single element tuple as opposed to a string.
The documentation clearly says:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
Unpacking multi-element tuple:
a, b = (12, 14)
print(type(a))
Output:
int
Unpacking single-element tuple:
a, = (12, )
print(type(a))
Output:
int
Otherwise:
a = (12,)
print(type(a))
Output:
tuple
In the question's example, you assigned the variable 'abc' to a Tuple with a length of 1.
You can do multiple assignments with this similar syntax:
x,y = 20,50
Also note that the print statement has a special understanding for ending a print statement with a comma; This tells print to omit the trailing newline.
print 'hello',
print 'world'
result:
hello world
I was somewhat confused about the application of the comma, as you also apply a comma to make a list instead of tuple, but with a different variable assignment.
Hereby, a simple example that I made of how to create a tuple or a list.
abc = 1,2,3 # prints a tuple: (1, 2, 3)
*abc, = 1,2,3 # prints a list: [1, 2, 3]
This question already has answers here:
What is the syntax rule for having trailing commas in tuple definitions?
(10 answers)
Closed 5 months ago.
First, I've sorted out my issue when I found this:
in python: iterate over each string in a list
Originally I was getting what I thought was weird behavior when I would iterate over a "list" with a single string. In those instances, the string was being treated as a group of characters, and the iteration was sequentially returning each character in the string.
Being new to Python, I did not realize there's a somewhat strict difference between using [] and () to define a list. My list definitions were using (). However, when the lists would contain more than one string, the iteration was return each complete string sequentially. To illustrate:
list = ('string')
for i in list:
print i
Output:
s
t
r
i
n
g
But if i do this, that is, add a second string to the () group:
list = ('string','another string')
for i in list:
print i
It gets treated as if I used [] (as you're supposed to). Output:
string
another string
Now, I get the expected behavior either way if I use [] to define my lists, so that's what I'm doing now. I just thought this was interesting behavior.
Can someone point me towards some documentation that explains the way Python interprets parens, especially relative to strings?
I didn't see anything in the Python docs for data structures:
https://docs.python.org/3/tutorial/datastructures.html
Thanks!
That's because parentheses don't define lists. They sometimes define tuples (a, b), which are similar to lists, but even in the code you provide, that is not a tuple.
('string')
Is a parenthesized expression. It's value is 'string'.
('string',)
Is a 1-tuple that contains a single element, the string 'string'
In the first case, the parenthesis are ambiguous. Do you mean a single element tuple or do you mean a parenthesized expression? The Python parser assumes parenthesized expression. You then are iterating over the string:
>>> li = ('string')
>>> li
'string'
This is in contrast to creating a list literal or set literal with a single string literal since there is no ambiguity what you mean:
>>> ['string']
['string']
>>> {'string'}
set(['string'])
In the second case, you are creating a tuple with two elements and then iterating over that tuple:
>>> li = ('string','another string')
>>> li
('string', 'another string')
If you want the first case to act like the second case, add a comma to create a one element tuple:
>>> li = ('string',)
>>> li
('string',)
Or, you do not have to use parenthesis to define a tuple:
>>> 'string','another string'
('string', 'another string')
>>> 'string',
('string',)
The tuple constructor in this case is the comma which allows this idiom in Python for swapping values without a temporary variable:
>>> a='string'
>>> b='another string'
>>> a,b=b,a
>>> a
'another string'
>>> b
'string'
(And please do not use list as a variable name. That redefines the list function...)
Why does adding a trailing comma after an expression create a tuple with the expression's value? E.g. in this code:
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
Why is the printed output ('mystring',), and not just mystring?
It is the commas, not the parentheses, which are significant. The Python tutorial says:
A tuple consists of a number of values separated by commas
Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.
See the Python Tutorial section on Tuples and Sequences
Because this is the only way to write a tuple literal with one element. For list literals, the necessary brackets make the syntax unique, but because parantheses can also denote grouping, enclosing an expression in parentheses doesn't turn it into a tuple: you need a different syntactic element, in this case the comma.
Make sure to read this great answer by Ben James.
Tuples are not indicated by the parentheses. Any expression can be enclosed in parentheses, this is nothing special to tuples. It just happens that it is almost always necessary to use parentheses because it would otherwise be ambiguous, which is why the __str__ and __repr__ methods on a tuple will show them.
For instance:
abc = ('my', 'string')
abc = 'my', 'string'
What about single element tuples?
abc = ('mystring',)
abc = 'mystring',
So in effect what you were doing was to create a single element tuple as opposed to a string.
The documentation clearly says:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
Unpacking multi-element tuple:
a, b = (12, 14)
print(type(a))
Output:
int
Unpacking single-element tuple:
a, = (12, )
print(type(a))
Output:
int
Otherwise:
a = (12,)
print(type(a))
Output:
tuple
In the question's example, you assigned the variable 'abc' to a Tuple with a length of 1.
You can do multiple assignments with this similar syntax:
x,y = 20,50
Also note that the print statement has a special understanding for ending a print statement with a comma; This tells print to omit the trailing newline.
print 'hello',
print 'world'
result:
hello world
I was somewhat confused about the application of the comma, as you also apply a comma to make a list instead of tuple, but with a different variable assignment.
Hereby, a simple example that I made of how to create a tuple or a list.
abc = 1,2,3 # prints a tuple: (1, 2, 3)
*abc, = 1,2,3 # prints a list: [1, 2, 3]
I've got a dict in which I load some info, among others a name which is a plain string. But somehow, when I assign it to a key in the dict it gets converted to a tuple, and I have no idea why.
Here's some of my code:
sentTo = str(sentTo)
print type(sentTo), sentTo
ticketJson['sentTo'] = sentTo,
print type(ticketJson['sentTo']), ticketJson['sentTo']
which outputs the following on my terminal:
<type 'str'> Pete Chasin
<type 'tuple'> ('Pete Chasin',)
Why does assigning it to a dict convert it to a tuple?
You told Python to create a tuple containing a string:
ticketJson['sentTo'] = sentTo,
# ^
It is the comma that defines a tuple. Parentheses are only needed to disambiguate a tuple from other uses of a comma, such as in a function call.
From the Parenthesized forms section:
Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.
and from Expression lists:
An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
ticketJson['sentTo'] = sentTo, is single element tuple