Why is the output of the code 9? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is the output of the code 9?

a = [2, 1, 2, 4] a[1:].remove(2) print(sum(a))

13th Jul 2023, 10:47 AM
eMBee
eMBee - avatar
6 Answers
+ 2
Mofetoluwa Balogun , I assume you're trying to remove the second instance of 2 without using pop(), because maybe you don't know the index in some hypothetical scenario. I thought of something. It won't work on a list with three 2s though. https://code.sololearn.com/cr4b3uslvWjp/?ref=app
30th Aug 2023, 4:23 PM
Rain
Rain - avatar
+ 7
The print is calling for the sum of the list before it was altered. The alteration has created a new object with a different ID. The original ID is referenced by the last line of code. Refer to attached code for details https://code.sololearn.com/ctHZ7jTTfS5E/?ref=app
13th Jul 2023, 10:59 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Thanks, Rain that's exactly the answer I needed
30th Aug 2023, 5:10 PM
eMBee
eMBee - avatar
+ 1
Mofetoluwa Balogun , Cool. 😎
30th Aug 2023, 6:04 PM
Rain
Rain - avatar
0
Rik Wittkopp So how do I do it to actually make it print the correct value after it is altered?
13th Jul 2023, 11:31 AM
eMBee
eMBee - avatar
0
Input is not take in C language
14th Jul 2023, 6:43 AM
Kapil Prajapat
Kapil Prajapat - avatar