2

I am printing the list variable as:

lst=("Python",)*3
print(lst)
lst=("Python")*3
print(lst)

and the output is

('Python', 'Python', 'Python')
PythonPythonPython

Definitely the output is different due to the comma(,) used in the first print statement. But the first statement does not have two values either.

Can someone describe the technical reason behind this?

5
  • ("Python",) creates a 1-tuple and ("Python") is just a string in brackets. In fact, the brackets don't do anything here, just "Python", will create the same tuple. As a side note, () will create an empty tuple. Commented Feb 11, 2018 at 5:19
  • Adding the comma just makes it a tuple. ("1", "2") * 2 = ("1", "2", "1", "2") Commented Feb 11, 2018 at 5:21
  • This page has a bit more detail on tuple syntax, wiki.python.org/moin/TupleSyntax. Commented Feb 11, 2018 at 5:23
  • Thanks @Wright, This solve my confusion Commented Feb 11, 2018 at 11:11
  • Thanks @eugenhu for clearing my confusion Commented Feb 11, 2018 at 11:12

1 Answer 1

2

TL;DR:

A trailing , creates a tuple

Tuples:

"Python",

is a tuple of length 1, so

lst=("Python",)*3

Is a tuple of length 3:

('Python', 'Python', 'Python')

Strings:

("Python")

is a string, and thus:

lst=("Python")*3

is a string that is repeated three times:

PythonPythonPython
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.