• edited by
214 views
2 2 votes

Consider the following Python code:

s = [9, 7, 8]

a, b = s, s[:]

print(a is s, b == s, b is s)
print(a.pop())
print(a + b)

What is the output of the code above?

  1. True True True
    8
    [9, 7, 9, 7]
  2. True True False
    8
    [9, 7, 9, 7, 8]
  3. False True False
    8
    [9, 7, 8, 9, 7, 8]
  4. True False False
    7
    [9, 8, 9, 7, 8]

3 Answers

0 0 votes

B. True True False

8

[9, 7, 9, 7, 8]

a,b = s,s[:] # Here reference to s gets copied to a, but a shallow copy is created for all elements of s and reference is stored in b.

Shallow Copy: Only the copy of the container object is made, references to internal elements remain the same. If internal elements are changed by reference, changes will reflect in all shallow copies. 

a is s, b == s, b is s 

x == y : Compare by values, return true if all are equal

x is y : Return true if x and y point to the same object (container)
Since b is a shallow copy, it points to a different container but is equal to a by value. 

a.pop() only changes the container a, popping 8. Since b has a different container and reference to 8 was not changed inside b, it will not change. (Note: Constants are immutable in python. Changing constants or immutable data structures in any shallow copy will change the reference inside the new container, not affecting the original values. But reference data structures like lists, maps will reflect changes in all shallow copies.)

$\therefore a+b\ is\ [9,7,9,7,8]$  

0 0 votes

Initially:

s = [9, 7, 8]

Now:

a, b = s, s[:]

Here, $\texttt{a}$ refers to the same list as $\texttt{s}$, but $\texttt{b}$ is a sliced copy.

a is s     True
b == s     True
b is s     False

Then:

a.pop()

Since $\texttt{a}$ and $\texttt{s}$ refer to the same list, this removes $8$ from $\texttt{a}$ and $\texttt{s}$.

a = [9, 7]
b = [9, 7, 8]

So:

a + b = [9, 7, 9, 7, 8]

Final output:

True True False
8
[9, 7, 9, 7, 8]
Answer:
Position:
Show:

Related questions

2 2 votes
3 3 answers
237
237 views
GO Classes asked Jul 2
237 views
A function $\texttt{shuffle(s)}$ takes a sequence $\texttt{s}$ with an even number of elements. It returns a new list by interleaving the first half of $\texttt{s}$ with ...
2 2 votes
3 3 answers
188
188 views
GO Classes asked Jul 2
188 views
Consider the following Python code:s = [3] s.extend([4, 5]) s.extend([s.append(9), s.append(10)]) print(s)What is the output of the code above?[3, 4, 5, 9, 10][3, 4, 5, N...
2 2 votes
2 2 answers
249
249 views
GO Classes asked Jul 2
249 views
A function $\texttt{deep_map(f, s)}$ replaces every non-list element $\texttt{x}$ inside a nested list $\texttt{​​​​​​​s}$ with $\texttt{f(x)}$.It modifies $\texttt{​​​​​...
2 2 votes
3 3 answers
253
253 views
GO Classes asked Jul 2
253 views
Consider the following Python code:s = [6, 7, 8] print(s.append(6)) s.insert(0, 9) x = s.pop(1) s.remove(x) print(s)What is the output of the code above?None [9, 7, 8]Non...