-1

Can someone explain variable assignments in python? i understand that a variable is tagged to a location in memory, thus multiple variables can be tagged to the same location.

What are the implications of this? Aside from mutating compound data types, thus changing all the pointing variables, are there any others?

Is there any situations where this is relevant when not mutating compound data types?

Thanks

KGS
  • 277
  • 2
  • 4
  • 11
  • possible duplicate of [Python: How do I pass a variable by reference?](http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference) – Mp0int Feb 28 '14 at 15:19

1 Answers1

0

I think that this question is a bit too broad for the SO format. The space of "possible things you could do with multiple references to the same object" is large. But regardless, yes, there are more possible uses (and abuses) than making multiple references to a mutable data type.

You can, for example, usefully make multiple references to an object that maintains state (like a generator) and access your references in order, perhaps doing something different with each. One "cute trick" that comes up fairly often is the following method to "chunk" an iterable into n pieces:

s = 'this is a string'

its = [iter(s)] * 2

zip(*its)
Out[17]: 
[('t', 'h'),
 ('i', 's'),
 (' ', 'i'),
 ('s', ' '),
 ('a', ' '),
 ('s', 't'),
 ('r', 'i'),
 ('n', 'g')]

Obviously you don't need the ability to make multiple references to the same iterator to accomplish this task, but python lets you do it. This type of approach could be useful if you want to "striate" a file-like-object, or something along those lines.

As for "gotchas", or things you need to watch out for, they are mostly riffs on the same issue. How do I make a multidimensional list in the python programming FAQ covers it pretty well.

roippi
  • 25,533
  • 4
  • 48
  • 73