What will be the output of the following Python code? [code] names1 = ['Amir', 'Bear', 'Charlton', 'Daman'] names2 = names1 names3 = names1[:] n

Khang Lê

New member
What will be the output of the following Python code?
Code:
names1 = ['Amir', 'Bear', 'Charlton', 'Daman']
names2 = names1
names3 = names1[:]
names2[0] = 'Alice'
names3[1] = 'Bob'
sum = 0
for ls in (names1, names2, names3):
    if ls[0] == 'Alice':
        sum += 1
    if ls[1] == 'Bob':
        sum += 10
print sum
A. 11
B. 12
C. 21
D. 22
 
Answer: b
Explanation: When assigning names1 to names2, we create a second reference to the same list. Changes to names2 affect names1. When assigning the slice of all elements in names1 to names3, we are creating a full copy of names1 which can be modified independently.
 

Tìm kiếm

Back
Top