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

  • Context: Python 
  • Thread starter Thread starter nrqed
  • Start date Start date
  • Tags Tags
    Python
Click For Summary

Discussion Overview

The discussion revolves around the differences between using parentheses and square brackets in Python, specifically focusing on the definitions and behaviors of tuples and lists. Participants explore the implications of these data structures in coding practices, including how they can be manipulated and combined.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • Some participants explain that parentheses define a tuple, while square brackets define a list, noting that tuples are immutable and lists are mutable.
  • Examples are provided to illustrate the immutability of tuples and the mutability of lists, including attempts to modify elements and the resulting errors.
  • There is a discussion about the use of tuples and lists in appending operations, with some participants questioning whether converting a list to a tuple before appending changes how the elements are stored in the list.
  • Some participants clarify that appending a tuple to a list results in the tuple being treated as a single element within the list, rather than merging the elements of the tuple into the list.
  • Redundant parentheses in certain expressions are discussed, with participants noting that they can be used for clarity or to group expressions, but may not always be necessary.

Areas of Agreement / Disagreement

Participants generally agree on the definitions and basic behaviors of tuples and lists, but there is some disagreement regarding the implications of converting lists to tuples when appending them to other lists. The discussion remains unresolved on the necessity and effects of such conversions.

Contextual Notes

Some limitations in understanding arise from the complexity of how Python handles different data types and the nuances of appending operations. There are also unresolved questions about the rationale behind certain coding choices made by the original author of the code in question.

Who May Find This Useful

This discussion may be useful for Python programmers, particularly those interested in data structures and their behaviors, as well as individuals looking to understand the implications of using tuples versus lists in their code.

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
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 31 ·
2
Replies
31
Views
7K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 0 ·
Replies
0
Views
2K
  • · Replies 14 ·
Replies
14
Views
2K
  • · Replies 13 ·
Replies
13
Views
3K