Why the list creates in two different ways? Does it cause by the mutability of its elements? Where the Python document explains it?

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Jun 15 03:01:28 EDT 2021


On 15/06/21 3:18 pm, Jach Feng wrote:
> From a user's point, I don't really care how Python creates thoseinstances, > either using an already exist one or create a new one, as
> long as each element (and its sub-element) are independent from each
> other so a modification of one will not influence the other. The real
> problem is there are different methods can be used to build it and some
> will fail in this purpose. The * operator is one of them, but anyone
> else? I really like to know:-)

This really has nothing to do with how the tuples are created.
It all depends on what you choose to put in them.

When you use square brackets to build a list, you can be sure that
it will create a new list object each time.

Also, if you create two tuples, by any means, containing distinct
elements, you can be sure that you will get two distinct tuple
objects.

So, if you do this:

a = [1, 2]
b = [1, 2]
c = [1, 2]
d = [1, 2]

s = (a, b)
t = (c, d)

then you are guaranteed to get four different list objects and
two diffferent tuple objects.

Does that help to ease your fears?

-- 
Greg


More information about the Python-list mailing list