What is output of below snippet and how ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is output of below snippet and how ?

a=str([1,2,3,4]) print (len(a))

16th Apr 2023, 5:50 PM
Somvir Dhaka
Somvir Dhaka - avatar
18 Answers
+ 6
You can find out WHAT the output is by actually RUNNING the code. Count the number of characters in the string and you find out why it is like that.
16th Apr 2023, 6:07 PM
Lisa
Lisa - avatar
+ 4
print(a) Then count.
18th Apr 2023, 10:30 AM
Lisa
Lisa - avatar
+ 1
Output is expected when you run the code. If you get an error, LINK your complete code. Check the indentation. Check the spellings. Check for unmatched brackets.
18th Apr 2023, 10:10 AM
Lisa
Lisa - avatar
+ 1
Quoting myself: Count the number of characters in the string and you find out why it is like that.
18th Apr 2023, 10:18 AM
Lisa
Lisa - avatar
+ 1
space is inbuilt here if we use 2 space then also it counts as 1 for ex a= str([2, 3, 4]) print(len(a)) ans is 9 if a= str([2,3,4]) print(len(a)) then also ans is 9
18th Apr 2023, 10:36 AM
Ritu Rani
0
Output is not expected please explain
17th Apr 2023, 2:26 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
I think output is 4
18th Apr 2023, 10:02 AM
Ritu Rani
0
How output is 12
18th Apr 2023, 10:14 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
no output is not 12 it's wrg
18th Apr 2023, 10:16 AM
Ritu Rani
0
Please run the code
18th Apr 2023, 10:16 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
Chara are 9 only
18th Apr 2023, 10:28 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
sry, output is 12 because if we convert the list to string then it counts character, comma, square bracket, and space also.. it counts 12 so ans is 12
18th Apr 2023, 10:30 AM
Ritu Rani
0
Where is space
18th Apr 2023, 10:31 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
or if we use no space then also it count 1
18th Apr 2023, 10:37 AM
Ritu Rani
0
Thanks Ritu Rani you are superb
18th Apr 2023, 10:43 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
I lv this compliment, thanks 🙂
18th Apr 2023, 11:31 AM
Ritu Rani
0
It appears that the python complier automatically adds a space after each ( , ) ; So, there is a total of 12 characters (including the opening and closing brackets, commas, spaces, and digits). 1. [ 2. 1 3. , 4. space 5. 2 6. , 7. space 8. 3 9. , 10. space 11. 4 12. ]
19th Apr 2023, 2:24 AM
Chris Coder
Chris Coder - avatar
0
I agree with Ritu rani Perhaps Python's list __str__ or __repr__ method always adds spacing between items. why not simply use print(len('[1,2,3,4]') or if you must use str() a=str([1,2,3,4]).replace(' ','') print(len(a))
19th Apr 2023, 2:49 AM
Bob_Li
Bob_Li - avatar