0

nums=[123] print(nums *3) gives o/p as {123123123} but print(nums[2]*3) gives o/p as {9} why don't op as {333}?

20th May 2017, 3:05 PM
sai charan tej
sai charan tej - avatar
2 Answers
+ 4
nums*3 tells Python to return 'the whole list' three times nums[2] tells it to return the third item of the list, which in this case will raise an IndexError, as you described a one-element list there :) You could address it as nums[0] which equals to 123. But that tells Python to return *the element* of the list. If you then multiply it by 3, you will get 369. If thia element was '123' instead of 123 (a string type instead of int), you'd get '123123123'.
20th May 2017, 8:25 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 2
This is because (nums[2]*3) is the same as (3*3)... and not as ("3"*3) which will output {333}
20th May 2017, 3:17 PM
Tim Thuma
Tim Thuma - avatar