0
vis1 = [0 for i in range(10)]
vis2 = [0] * 10

Result of these two lines is

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

When we execute

name = "ram" * 10

then it multiplies "ram" 10 times and returns whole string

ramramramramramramramramramram

So why the same is not happening with [0]*10 it should return 10 lists containing 0 according to similarity, Where i am going wrong ?

and Please explain the 1st line also i.e. vis1 = [0 for i in range(10)] Does it return 0 10 times inside the list while running loop or what else

  • 1
    ... When you multiple a string by 10, you get one string 10 times as long. When you multiple a list by 10 you get one list 10 times as long. It works just the same. – khelwood Oct 26 '22 at 15:14
  • 1
    If you want a list containing ten sublists, use `[[0]] * 10`. – John Gordon Oct 26 '22 at 15:15
  • 1
    Consider the result of `['r', 'a', 'm'] * 10`... – LinFelix Oct 26 '22 at 15:15
  • 1
    In python all things are objects so list and strings as well. So when you are multiplying them by some integer then they execute their respective `__mul__` magic methods that will tell what should happen when a particular list or str object is multiplied by some number . You can check its implementation in python docs – Deepak Tripathi Oct 26 '22 at 15:16
  • Read more on https://docs.python.org/3/library/stdtypes.html#common-sequence-operations – Deepak Tripathi Oct 26 '22 at 15:22

1 Answers1

2

You are not going anywhere wrong. I get the same result. I also intuitively expected that the vis2 would be [[0], [0], ..., [0]], but then again this is just my opinion vs. opinion of whoever designed this particular aspect of Python language. Somebody had to make this choice and this person did it for whatever reason they thought it makes sense.

If you want the result you expect, use [[0]]*10.

As for vis1, the range(10) is a generator that will emit numbers from 0 to 9, inclusive. Using a generator in a list comprehension expression such as [f(x) for x in ...] will simply iterate over the values returned by the generator (x), run each value through f (which is just 0 in your case) and collect the results in a list.

jurez
  • 4,436
  • 2
  • 12
  • 20
  • 3
    Caveat: `[[0]]*10` is a list containing ten references to the same inner list. See https://stackoverflow.com/q/240178/3890632 – khelwood Oct 26 '22 at 15:19