简体   繁体   中英

How to create a list with the element 0 n times? python

Is this the right way to go about it? Or does 0 also have to be in [] brackets?

list = [0 * i for i in range(n)]

If yes then how is it different from writing it like this right away?

list = [0]* n

Use [0] * n , where n is your desired no. of elements in the list.

In the first instance you are creating a list comprehension in which values within the range 0 to (n-1) are being inserted as elements into a list however they are also individually being multiplied by zero, leaving them as zero.

Whilst in the second instance which you had written as list = [0 * n] you are inserting a single value into a list: 0 multiplied by n - thus leaving the list length at 1.

(now you have adjusted it to match our answers)

ls = [0] * n

And now you have phrased your question as: Why is your list comprehension technique different to the, recently amended approach, of multiplying the list by n. This is because as previously mentioned in the list comprehension approach you are multiplying each element by zero before inserting it into the list, whilst the 2nd approach you are multiplying the entire list by n causing it to become length n, filled with zeros.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM