Home > Net >  Is it correct to create Tuples like this in a single Python program?
Is it correct to create Tuples like this in a single Python program?

Time:07-17

Can we create Tuples like this in a program,

mytuple = ("Rock", "Kane", "Undertaker")
print(mytuple)

mytuple = (2, 5, 7, 9, 15)
print(mytuple)

or, since Tuples cannot be modified, we should create a new Tuple object instead:

mytuple1 = ("Rock", "Kane", "Undertaker")
print(mytuple1)

mytuple2 = (2, 5, 7, 9, 15)
print(mytuple2)

Both the above programs ran successfully. Are both correct ways of creating Tuples?

CodePudding user response:

If you use curly brackets {} you are defining a set, not a tuple. Anyway, in both of your examples you are not modifying a variable, but you are redefining it. So of course it runs successfully.

An error would be raised if you try to do something like


mytuple = (1,2,3)
mytuple[0]= 5


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

CodePudding user response:

In the first example, you are allocating the single variable mytuple in memory and changing the content inside.

In the second example, you are allocating two variables (mytuple1 and mytuple2).

The difference is that, in the first case, you won't have access to the previous value ("Rock", "Kane", "Undertaker"), while in the second case both tuples will be available under different variable names.

A rule of thumb would be: if you don't need the previous value, you can reassign the variable (as in the first example) to minimize memory usage.

  • Related