Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 14 Online
OpenStudy (anonymous):

For problem set 3 problem 2, how would you create the tuple? Tuples are immutable so you wouldn't be able to create a loop that adds locations to the tuple. You can't create variables of the locations of each key because you don't know how many instances there are. Please help

OpenStudy (anonymous):

you can either use a list, and append locations to it, then make the tuple from the list, or you can have a variable that refers to the tuple and just create new tuples to add the location: #with list locs = [] for i in range(5): locs.append(2*i) print tuple(locs) #with tuple locs = () for i in range(5): locs = locs + (3*i,) print locs

OpenStudy (anonymous):

Oh, so you can add to a tuple? It's called immutable so I just assumed it couldn't be changed at all once created. Thanks polpak

OpenStudy (anonymous):

No you cannot add to it. I thought that is what I said. You can create a new tuple whos elements are taken from another tuple though. Notice in my tuple example I'm saying: locs = locs + (3*i,) This creates a new tuple whos contents are taken as all the elements in locs and all the elements in the second tuple. Then it re-assigns the name locs to reference this new tuple instead of the original one.

OpenStudy (anonymous):

Numeric data types and strings are also immutable, but that doesn't stop you from saying: i = 5 i = i + 1 or s = 'ham' s = s + ' and eggs' Because again, you're constructing a new object from other data, then re-assigning the object your name references to the new one you just created.

OpenStudy (anonymous):

For a better understanding, consider this code: t1 = (1,2,3) t2 = t1 print t1, t2 print id(t1), id(t2) t2 = t2 + (4,) print t1, t2 print id(t1), id(t2) # Versus l1 = [1,2,3] l2 = l1 print l1, l2 print id(l1), id(l2) l2.append(4) print l1,l2 print id(l1), id(l2)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!