Computer Science, asked by rohillapranjay, 21 hours ago

Please tell the following

Attachments:

Answers

Answered by Equestriadash
5

Given co‎ding:

l = [1, 2, 3, 4, 5, 6]

ol = l

l.remove(max(l))

m2 = max(l)

print("The second largest element from", ol, ":\n", m2)

The above coding would print 5 as the largest number. However, as per your query, you expected 6 to be printed instead.

Let me explain the co‎des line by line.

#initializing a list with values

l = [1, 2, 3, 4, 5, 6]

#storing the list into another variable

ol = l

#removing the maximum value from the list 'l'

l.remove(max(l))

#printing the largest element

print("The second largest element from", ol, ":\n", m2)

Now, when you print 'ol', it would display [1, 2, 3, 4, 5].

While the 3rd command to remove the highest element was given, it is most likely that you expected the element to be removed only from the original list 'l' and not 'ol'.

When you store a list into another variable, any changes that occur to the original list, will also occur in the duplicate one.

So l.remove(max(l)) removed the highest element from both 'l' and 'ol' since they're the same elements.

In order to avoid this, Python has an in-built method called copy(). This method enables a programmer to store a copy of the list into a new variable, thereby discouraging any changes that are going to be made to the original list.

Taking our current situation as an example,

l = [1, 2, 3, 4, 5, 6]

ol = l.copy()

l.remove(max(l))

m2 = max(l)

print("The second largest element from", ol, ":\n", m2)

No changes will occur to 'ol' as it is only a copy of the list and is not actually interlinked with the original list 'l'.

Similar questions