What Is the Output of This python Code?
Question :
x = [1, 2, 3]
print(len(x + [4, 5]))
Options :
A) 3
B) 4
C) 5
D) Error
Correct answer:
C) 5
Explanation:
First we create a list :
x = [1, 2, 3]
The list x contains 3 elements.
Step 1 - List Concatenation
x + [4, 5]
The + operator joins two lists together.
So python combines both lists:
[1, 2, 3] + [4, 5]
Result:
[1, 2, 3, 4, 5]
Step 2 - len ( ) Function
len(x + [4, 5])
The len ( ) function returns the number of elements in the list.
The new list contains:
1, 2, 3, 4, 5
Index positions :
Index : 0 1 2 3 4
Value : 1 2 3 4 5
so the list has 5 elements therefore:
len([1, 2, 3, 4, 5]) = 5
Total elements = 5
Final output:
5
Practice daily python coding challenges to improve your programming and logical thinking skills.
Happy coding ❤️

No comments:
Post a Comment