How did you figure out that (1,2) + (3,) gives you (1,2,3)?
Very interesting question . You deserve several medals for this one. The syntactical representation of lists and tuples in python are for the most part equivalent. But sometimes they are subtly different. Consider: x = [1,2] y = [3,4] x is a list, y is a list if i add (concatenate) x to y I also get a list x + y (equals) [1,2,3,4] The above pattern is exactly the same for tuples x = (1,2) y = (3,4) x is a tuple, y is a tuple if I add (concatenate) x to y I also get a tuple x+ y (equals) (1,2,3,4) Now consider: x =[1,2] y = [3] x is a list and so is y if I add (concatenate) x to y I also get a list x + y (equals) [1,2,3] But now it gets interesting. If I declare: x =(1,2) y=(3) and add x + y, I would expect it to give me the tuple: (1,2,3). Try it and you will get a "type error". Why? The statement y=(3) looks like you are declaring a tuple with one member, 3. But y it turns out is not a tuple at all. It's just 3. If you want a tuple with one member then you have to declare it as y = (3,) Then you can go ahead an add x to y and you will get: (1,2,3). Excellent Question!
wow, the line of thinking makes terrific sense. y=(3) is not a tuple, and now I see that because parenthesis are used as a arithmetical operator, unless you include a comma. brackets on the other hand are not used with arithmetic operations. Apparently, this can be illustrated by the two expressions: >>> (1+2)*3 9 >>> [1+2]*3 [3, 3, 3] Thanks!
To reinforce the point, if you type in the interpreter x =[1] y=1 x==y you will get False It's what we would expect since x is a list with one member, namely 1 and y is the number 1. x and y are not the same but if you type x=(1) y=1 x==y you will get True because x is 1 and y is also 1 one is deceived into thinking that we are creating a tuple with the statement x=(1) in the statement above x=(1) is equivalent to x=1
no need for further reinforcement, though what you say all seems to be true. i believe your first reply made a light switch come on in my head. thanks again!
I read this section: "A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective." and immediately favorited the link you sent as a resource for python. Thanks bwCA!
that documentation should be installed on your computer. If using windows and idle, F1 from within idle.
Join our real-time social learning platform and learn together with your friends!