Python What is the difference between using parentheses and square brackets in Python?

  • Thread starter Thread starter nrqed
  • Start date Start date
  • Tags Tags
    Python
Click For Summary
In this discussion, a user seeks clarification on the difference between tuples and lists in Python, specifically regarding the syntax of parentheses and square brackets. It is explained that parentheses create a tuple, which is immutable, meaning its elements cannot be changed after creation, while square brackets create a list, which is mutable and allows for element modification. The conversation also touches on the use of tuples when appending to lists, noting that converting a list to a tuple before appending results in the entire tuple being added as a single element, rather than its individual elements being added separately. This behavior is contrasted with appending a list directly, which would result in a nested list structure. The original programmer's choice to use tuples is suggested to be for making data read-only. The user expresses appreciation for the insights and plans to explore more Python concepts in the future.
nrqed
Science Advisor
Messages
3,762
Reaction score
297
Hopefully someone (chroot??) wil be able to answer this simple Python question.

I am looking at a code written by someone else and there are those two enigmatic statements one after the other:

link0=(0,0,0,0)
pathlist=[link0]


Ok, besides the obvious question of why not initializing directly the list "pathlist" to 0,0,0,0 (it's hard to know what was going in someone's else mind when they were writing the code so I don't worry too much about that point...sometimes code are rewritten and modified over and over before reaching their final form and not everything is rewritten to be the simplest), I have this more to the point question:

what is the difference between defining something within parenthesis (...) and within square brackets [..]? I think that in the second case we are dealing with a list object so that all the corresponding methods (like append) can be used. But what kind of object is (...) ? I am not sure if it simply a string, and if it is I am not sure what the difference is between a string and a list (different methods are defined?)

Thanks in advance!

Patrick
 
Technology news on Phys.org
Hi Patrick,

Parentheses define a "tuple", square brackets a "list". They're both superficially similar to arrays in Fortran, C, etc. Tuples are immutable. That is, once you've created a tuple, you can't change it. You can't add or delete elements, and you cannot assign to elements.

For example,
>>> a = (1,2,3)
>>> a[1] = 3
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
a[1] = 3
TypeError: object does not support item assignment
>>> print a
(1, 2, 3)

With a list, one can assign new values to elements, add or remove elements, and so on.

>>> b = [1,2,3]
>>> b[1] = 4
>>> print b
[1, 4, 3]
>>> b.append(6)
>>> print b
[1, 4, 3, 6]

A string is a different type. You can find out what attributes an object has by typing dir( <object>):
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__str__']

And you can find out its type--"introspection":
>>> a.__class__
<type 'tuple'>
>>> a.__class__.__name__
'tuple'

Very powerful.

Hope that helps.
Tim
 
nmtim said:
Hi Patrick,

Parentheses define a "tuple", square brackets a "list". They're both superficially similar to arrays in Fortran, C, etc. Tuples are immutable. That is, once you've created a tuple, you can't change it. You can't add or delete elements, and you cannot assign to elements.

For example,
>>> a = (1,2,3)
>>> a[1] = 3
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
a[1] = 3
TypeError: object does not support item assignment
>>> print a
(1, 2, 3)

With a list, one can assign new values to elements, add or remove elements, and so on.

>>> b = [1,2,3]
>>> b[1] = 4
>>> print b
[1, 4, 3]
>>> b.append(6)
>>> print b
[1, 4, 3, 6]

A string is a different type. You can find out what attributes an object has by typing dir( <object>):
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__str__']

And you can find out its type--"introspection":
>>> a.__class__
<type 'tuple'>
>>> a.__class__.__name__
'tuple'

Very powerful.

Hope that helps.
Tim
Wow! I appreciate it very much Tim! That is not just helpful, it is enlightening!

Thanks a lot for taking the time to post this.

That brings me to another point. I saw in the program (written by someone else, as I mentioned) the following: sometimes a list is appended to another list in the following way:

listone.append((tuple(listnumbertwo)...))

so it seems as if a list must be turned into a tuple before being appended to another list? Is that the correct interpretation?
(and is there a reason for the double parenthesis or one of the two is redundant?)

thank you very much!

Patrick
 
listOne.append( _(_ tuple( listNumberTwo)... _)_ )

List elements can be of any type, including lists:
Code:
>>> mylist = [1, "Four score", [1,1,2,3,5], ("j","k","l")]
The parentheses that I've "underlined" are redundant only if there's nothing after tuple( listNumberTwo). Surrounding a sequence of objects with parens is one way of declaring a tuple; the other way is to use the "tuple( sequence, of, things)" construct.

Suppose the whole thing looks like this:
Code:
listOne.append(  ( tuple( listNumberTwo),  3.14159, "Today is the greatest") )
This statement means:
  1. Convert listNTwo to a tuple
  2. Make a second tuple out of the first tuple, the floating point # 3.14159, and the string
  3. append that second tuple to listOne

It could have been written
Code:
listOne.append(  tuple( tuple( listNumberTwo),  3.14159, "Today is the greatest") )
One of the very powerful features of Python is this ability of containers can hold a mixture of any data types (even functions!). You can do this in C (of course, since Python is written in C), but it takes a bit of ingenuity, and if you do it well, you'll probably come up with a language like Python.

Tim
 
nmtim said:
List elements can be of any type, including lists:
Code:
>>> mylist = [1, "Four score", [1,1,2,3,5], ("j","k","l")]
The parentheses that I've "underlined" are redundant only if there's nothing after tuple( listNumberTwo). Surrounding a sequence of objects with parens is one way of declaring a tuple; the other way is to use the "tuple( sequence, of, things)" construct.

Suppose the whole thing looks like this:
Code:
listOne.append(  ( tuple( listNumberTwo),  3.14159, "Today is the greatest") )
This statement means:
  1. Convert listNTwo to a tuple
  2. Make a second tuple out of the first tuple, the floating point # 3.14159, and the string
  3. append that second tuple to listOne

It could have been written
Code:
listOne.append(  tuple( tuple( listNumberTwo),  3.14159, "Today is the greatest") )
One of the very powerful features of Python is this ability of containers can hold a mixture of any data types (even functions!). You can do this in C (of course, since Python is written in C), but it takes a bit of ingenuity, and if you do it well, you'll probably come up with a language like Python.

Tim

Thanks Tim! That is very useful! I really appreciate it very much .

That makes sense now.

But since one can append a list to another list, then there must be a reason to convert it to a tuple before appending, right? My guess is that if a list "listTwo" is converted to a tuple before being appended to "listOne", then each element of listTwo becomes an element of listOne, right? For example, if listOne is initially [1,2,3] and one appends tuple([4.5.6]) then ListOne becomes [1,2,3,4,5,6] and then one can access each element as a separate entry, whereas appending the list [4,5,6] would result into listOne becoming [1,2,3,[4,5,6]] which would be quite a different beast. Is that correct? Then I would understand why the guy who wrote the program had to convert all those lists into tuples before appending.

Thanks a whole lot!

Patrick
 
My guess is that if a list "listTwo" is converted to a tuple before being appended to "listOne", then each element of listTwo becomes an element of listOne, right?

Nope. The tuple formed from the elements of list two becomes a single element in list 1.
>>> one = [1,2,3]
>>> twoL = [4,5,6]
>>> twoT = tuple( twoL)
>>> print twoT
(4, 5, 6)
>>> one.append( twoT)
>>> print one
[1, 2, 3, (4, 5, 6)]
>>> print one[3]
(4, 5, 6)
I'm not sure why the original programmer chose to use a tuple. Typically, you do that to make the thing sort of "read-only".

By the way, are you using a Python shell to check this out? One of the great things about Python versus C, Fortran, etc. is you can always try out a bit of code and immediately see what it does in the interpreter.
 
nmtim said:
Nope. The tuple formed from the elements of list two becomes a single element in list 1.
>>> one = [1,2,3]
>>> twoL = [4,5,6]
>>> twoT = tuple( twoL)
>>> print twoT
(4, 5, 6)
>>> one.append( twoT)
>>> print one
[1, 2, 3, (4, 5, 6)]
>>> print one[3]
(4, 5, 6)
I'm not sure why the original programmer chose to use a tuple. Typically, you do that to make the thing sort of "read-only".

By the way, are you using a Python shell to check this out? One of the great things about Python versus C, Fortran, etc. is you can always try out a bit of code and immediately see what it does in the interpreter.
Hi Tim. Thank you very much, once again!
And thanks for the suggestion concerning using the Python shell. I have it installed on my desktop but I keep forgetting about using it to test how things work.

It is always confusing to try to understand someone else's code especially when one does not know the language. So I appreciate your comments. it helps me move along instead of staying stuck on details.

I will surely have more Python questions as I dig in the program more and start writing my own code so I hope you will stick around!

Many thanks again for your time!

Regards,

Patrick
 

Similar threads

  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
2
Views
2K
  • · Replies 31 ·
2
Replies
31
Views
7K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 0 ·
Replies
0
Views
1K
  • · Replies 14 ·
Replies
14
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K