89 views
0 0 votes

Consider the following Python code:

nums = [1, 2, 3]
it = iter(nums)

first = next(it)
nums.append(4)
second = list(it)

nums.append(5)
third = list(it)

print(first, second, third)

What is the output of the code above?

  1. 1 [2, 3] [4, 5]
  2. 1 [2, 3, 4] []
  3. 1 [2, 3, 4] [5]
  4. 1 [2, 3] []

1 Answer

0 0 votes

The statement $\texttt{it = iter(nums)}$ creates an iterator over the list.

The statement $\texttt{first = next(it)}$ takes the first value from the iterator.

first = 1

Now the iterator is positioned after $\texttt{1}$.

Then $\texttt{nums.append(4)}$ adds $\texttt{4}$ before the remaining iterator values are consumed.

So $\texttt{second = list(it)}$ collects the remaining values:

[2, 3, 4]

After this, the iterator is exhausted.

Even though $\texttt{nums.append(5)}$ adds a new value later, the exhausted iterator cannot be reused.

Therefore, $\texttt{third = list(it)}$ gives an empty list.

The final output is:

1 [2, 3, 4] []

Correct Option: B

Answer:
Position:
Show:

Related questions

1 1 vote
1 1 answer
114
114 views
GO Classes asked Jun 6
114 views
Consider the following Python code:def evaluate(x): try: if x == 0: return "zero" return "value" finally: x += 1 if x == 1: return "changed" print(evaluate(0), evaluate(2...
1 1 vote
1 1 answer
91
91 views
GO Classes asked Jun 6
91 views
Consider the following Python code:def make_funcs(): funcs = [] total = 0 for i in range(3): def add(x, step=i): nonlocal total total += x + step return total funcs.appen...
1 1 vote
1 1 answer
89
89 views
GO Classes asked Jun 6
89 views
Consider the following Python code:class Counter: count = [] def __init__(self, value): self.value = value def add(self): self.count.append(self.value) self.value += 1 re...
0 0 votes
1 1 answer
98
98 views
GO Classes asked Jun 6
98 views
Consider the following Python code:data = {"a": , "b": } x = data.setdefault("c", data["a"]) x.append(3) data["a"].append(4) data["b"] = data["a"][:] data["b"].append(5...