0

I'm completely new to programming. I am using vscode and have python 3.10.5,I am following no starch press crash course in python (2nd edition) and in the section on lists it tells me that a list in python is written between square brackets, separated by commas, like the following:

list1 = ['a', 'b', 'c'] 

When I print this I get back the square brackets and the stuff inside, which is all fine. I was playing around and wrote the following (expecting an error)

list2 = 'a', 'b', 'c' 

But when I print this, instead of an error I get back the right hand side but inside of round brackets.

What type of thing have I defined in list2?

5
  • 6
    Do a print(type(list2)) and you'll see it's a tuple. If you haven't done so yet and you're sticking with Python, I'd recommend going through the Python tutorial. Commented Aug 17, 2022 at 21:17
  • That's great, thank you very much. I see in the documentation that tuples are usually written using round brackets, but I didn't use any in my list2, is this 'wrong' somehow? Commented Aug 17, 2022 at 21:24
  • A tuple is like a list except that you can't change it after its been created. Commented Aug 17, 2022 at 21:24
  • 1
    Parens ( and ) are used to group things. The commas make the tuple and the parens are only needed if the commas are ambiguous syntactically. Lets say I want to call a function with a tuple, but the function syntax also uses commas to separate parameters., I'd have to put the tuple in its own paren. Commented Aug 17, 2022 at 21:25
  • From the documentation: "As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression)." (docs.python.org/3/tutorial/…) Commented Aug 17, 2022 at 21:26

2 Answers 2

1

You can always run type(variable) to check the variable type. In this case, a "list" without brackets is not a list, it's a tuple.

From the docs:

A tuple consists of a number of values separated by commas.

Parentheses are not required, though you will have to use them when building complex data structures, with nested tuples for example.

Reference: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences

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

Comments

0

It's because the list1 you created is recognized by the compiler as list (because you used square brackets which is mandatory) but list2 is recognized as a tuple because in python the parentheses are optional while creating a tuple, however, it is a good practice to use them.

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.