How does Python initialize a list to zero by a certain length?

Asked 1 years ago, Updated 1 years ago, 91 views

In C/C++,

int myarr[100] = {};

If you write it like this, all 100 elements have been initialized to zero In the Python list,

mylist = [0 for i in range(100)]

Is this the most Python way to write a for sentence? I'm curious because I don't think it's good to go around the For door.

python list-comprehension operator-overloading multiplication

2022-09-22 13:05

1 Answers

In addition to the method you filled out

mylist = [0]*100

We can do it together. If you expand and use it a little more, to display any item e times n

mylist = [e] * n

You can use it together, but you should be careful at this time because ne is not independent of each other and is the same n reference, so the programmer may have unexpected results.

For more information, this question I changed only one element in the list, but the whole element changed. Why? Please check it out at .


2022-09-22 13:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.