Python: (a,b,c) vs [a,b,c]

  • Thread starter nrqed
  • Start date
  • Tags
    Python
In summary, the author is looking at a code written by someone else and there are those two enigmatic statements one after the other: one is "sometimes a list is appended to another list in the following way: listone.append((tuple(listNumberTwo)...))", and the second is "so it seems as if a list must be turned into a tuple before being appended to another list?" The difference between the two is that the first is a tuple and the second is a list. Tuples are immutable, while lists can be modified.
  • #1
nrqed
Science Advisor
Homework Helper
Gold Member
3,766
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
  • #2
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
 
  • #3
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
 
  • #4
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
 
  • #5
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
 
  • #6
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.
 
  • #7
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
 

1. What is the difference between (a,b,c) and [a,b,c] in Python?

The main difference between (a,b,c) and [a,b,c] in Python is the data type they represent. The parentheses () represent a tuple, which is an immutable sequence of values, while the brackets [] represent a list, which is a mutable sequence of values.

2. When should I use a tuple instead of a list in Python?

Tuples are often used for data that will not change, such as coordinates or settings. They are also used to return multiple values from a function. Lists, on the other hand, are more versatile and can be modified. They are commonly used for storing and manipulating data.

3. Can I convert a tuple to a list and vice versa in Python?

Yes, you can use the built-in functions list() and tuple() to convert between tuples and lists. For example, list((1,2,3)) will return [1,2,3] and tuple([4,5,6]) will return (4,5,6).

4. Is there a performance difference between tuples and lists in Python?

In general, tuples are slightly faster than lists because they are immutable and thus require less memory. However, the difference in performance is minimal and usually not noticeable unless you are working with very large data sets.

5. Can I use indexing and slicing on tuples and lists in Python?

Yes, both tuples and lists support indexing and slicing operations. For example, my_tuple[0] will return the first element in the tuple, and my_list[2:5] will return a sublist containing elements 3, 4, and 5 from the list.

Similar threads

  • Programming and Computer Science
Replies
10
Views
2K
  • Programming and Computer Science
Replies
1
Views
137
  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
Replies
2
Views
624
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
10
Views
4K
Back
Top