user3732361
user3732361

Reputation: 397

multiplication for lists in python

I know there is something obvious that I am missing but I would rather clear my confusion than to mug it up. why does the following code: [1]*5 return [1,1,1,1,1]

and not [5]

or

[[1],[1],[1],[1],[1]]

Upvotes: 0

Views: 46

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

Multiplication is defined for sequences in general, not just lists, regardless of the type of the contained values. Sure, [1] * 5 -> [5] makes sense for a list of int, but it's nonsensical for a list of str, or a str by itself.

They wanted a generic sequence handler that worked for sequences of all types, so they defined it as repeated concatenation, rather than element-wise arithmetic. As juanpa mentions in the comments, this makes for a consistent definition: seq + seq is concatenation, so seq * int is just seq + seq repeated int times (well, seq is repeated int times, with four virtual concatenations), the same way inta * intb is just inta + inta repeated intb times.

If you want element-wise arithmetic, take a look at numpy arrays.

Upvotes: 2

Related Questions