0

i`m solving a basic exercise about say what number is duplicated in a list.

def repeat(nums):
    for i in range(len(nums)):
        x = nums[i]
        lista2 = nums
        lista2.pop(i)
        for j in range(len(lista2)):
            y = lista2[j]
            if x == y:   
                return x

lista = [4,6,3,5,8,7,5,11] #The duplicated num is 5

print("Inicial list ", lista)
print("The duplicated is: ", repeat(lista)) #The function work but
print("List before function ", lista)       #Destroy the inicial list

This is the result:

Inicial list  [4, 6, 3, 5, 8, 7, 5, 11]
The duplicated is:  5
List before function  [6, 5, 7, 11]

I know that exist other ways to solve this exercise, but i wanna know why this function delete elements of the initial list if i just copy the initial list and delete elements of the copy, not the original. More, the function eliminate the odd index elements of the list, someone can explain me why and how can i fix this function?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 4
    You probably think `lista2 = nums` makes a copy of `nums`. This is not the case. You are just giving `nums` a second name. Please watch [this](https://www.youtube.com/watch?v=_AEJHKGk9ns) and everything will be clear. – timgeb Mar 20 '21 at 17:47
  • 1
    @timgeb There's also a text version of that talk: [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) – wjandrea Mar 20 '21 at 18:20
  • 1
    Did not know about the @NedBatchelder video, it’s brilliant, many thanks for the reference! And thank you Ned for the excellent presentation. – S3DEV Mar 20 '21 at 20:26

0 Answers0