131 views
2 2 votes

Consider the following Python code:

def insert_items(s, before, after):
    index = 0
    while index < len(s):
        if s[index] == before:
            s.insert(index + 1, after)
            index += 1
        index += 1
    return s

large_s = [1, 4, 8]

large_s2 = insert_items(large_s, 4, 4)
large_s3 = insert_items(large_s2, 4, 6)

print(large_s3)
print(large_s3 is large_s)

What is the output of the code above?

  1. [1, 4, 6, 4, 6, 8]
    True
  2. [1, 4, 4, 8]
    True
  3. [1, 4, 6, 4, 8]
    True
  4. [1, 4, 6, 6, 4, 8]
    False

2 Answers

0 0 votes

Initially:

large_s = [1, 4, 8]

First call:

large_s2 = insert_items(large_s, 4, 4)

This inserts $4$ after every existing $4$.

large_s = [1, 4, 4, 8]

Now second call:

large_s3 = insert_items(large_s2, 4, 6)

This inserts $6$ after each $4$.

large_s3 = [1, 4, 6, 4, 6, 8]

The function modifies the same original list in place, so:

large_s3 is large_s

is $\texttt{True}$.

Final output:

[1, 4, 6, 4, 6, 8]
True
Answer:
Position:
Show:

Related questions

1 1 vote
2 2 answers
149
149 views
GO Classes asked Jul 3
149 views
A grid contains '$\texttt{s}$' for sand, '$\texttt{r}$' for rock, and $\texttt{None}$ for empty.The operation $\texttt{jumpdown(grid, x, n)}$ works on one column $\texttt...
1 1 vote
2 2 answers
124
124 views
GO Classes asked Jul 3
124 views
Suppose $\texttt{zeroArray(3, 4)}$ creates a $2$D array with $3$ rows and $4$ columns, filled with zeros.Now consider:v = zeroArray(3, 4)Which expression correctly change...
2 2 votes
2 2 answers
130
130 views
GO Classes asked Jul 3
130 views
Consider the following Python code:def group_by(s, fn): grouped = {} for x in s: key = fn(x) if key in grouped: grouped[key].append(x) else: grouped[key] = [x] return gro...
2 2 votes
3 3 answers
144
144 views
GO Classes asked Jul 3
144 views
Consider the following Python code:def remove_dups(L1, L2): for e in L1: if e in L2: L1.remove(e) L1 = [1, 2, 3, 4] L2 = [1, 2, 5, 6] remove_dups(L1, L2) print(L1)What is...