The ole Repetion != Concatination pitfall

J

JChG

Well I started learning Python last week, and in my first experiment I
got caught when I changed:

sieve = [ {1:True} for x in range(r)]
to
sieve = [{1:True}] * r

I was expecting it to be equivalent to
sieve = [{1:True},{1:True},...]
but instead it's
t = [{1:True}]; sieve = [t,t,...]

Okay, I see this was discussed 13 years ago, and it's a deliberate
choice. There are other ways to do this.

But I'll still whine anyway...I'm not seeing where list repetition is
particularly useful, except when you want independent objects, like my
initialization of sieve above. Oh well, I guess I'll just avoid it.
 
S

Steven D'Aprano

But I'll still whine anyway...I'm not seeing where list repetition is
particularly useful, except when you want independent objects, like my
initialization of sieve above.


Or when the objects are immutable, like ints, strings or None.


pre_allocated = [None]*100
while condition:
i = get_index()
pre_allocated = get_result()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top