Exam4Training

What is the expected output of the following code?

What is the expected output of the following code?

x = [0, 1, 2]

x.insert(0, 1)

del x[1]

print(sum(x))
A . 3
B. 2
C. 4
D. 5

Answer: C

Explanation:

Topics: insert() del sum() list

Try it yourself:

x = [0, 1, 2]

x.insert(0, 1)

print(x) # [1, 0, 1, 2]

del x[1]

print(x) # [1, 1, 2]

print(sum(x)) # 4

insert() inserts an item at a given position.

The first argument is the index of the element before which to insert.

insert(0, 1) inserts 1 before index 0 (at the front of the list).

The del keyword deletes the given object.

In this case x[1]

The sum() function adds the items of a list (or a different iterable) and returns the sum.

Exit mobile version