Help! Python programmers.

IreshMM

Well-known member
  • Jan 20, 2014
    1,546
    444
    83
    Actually, I'm not an expert. So I need your help to understand this. :)
    Code:
    lst=[4, 5, 5, 4]
    nwlst=lst
    for i in lst:
        print i
        nwlst.remove(i)

    Expected result :
    4
    5
    5
    4

    but I got :

    4
    5

    Once I removed the statement : nwlst.remove(i)
    I got the expected result.

    Can anyone explain this? How this happens? :confused::confused::confused::confused::confused:
     

    charith84

    Well-known member
  • Jun 22, 2006
    10,397
    7,412
    113
    because when you call lst.remove(i) to remove an element from the array "lst" it will remove all the elements which equals to the i
    eg
    4, 5, 5, 4
    nwlst.remove(4):give you the result "5,5" (removed all "4" s in the array)
    try to remove it by array index
     
    Last edited:

    IreshMM

    Well-known member
  • Jan 20, 2014
    1,546
    444
    83
    because when you call lst.remove(i) to remove an element from the array "lst" it will remove all the elements which equals to the i
    eg
    4, 5, 5, 4
    nwlst.remove(4):give you the result "5,5" (removed all "4" s in the array)
    try to remove it by array index

    It removed only the first element. :)
    2m31avq.png


    nwlst.remove(i) has been called not lst.remove(i)

    Can you check that again? :)
     

    IreshMM

    Well-known member
  • Jan 20, 2014
    1,546
    444
    83
    Thank you everyone who replied and tried to help me
    :yes::yes::yes::yes::yes::yes::yes::yes::yes:

    Rep added​
     
    Last edited: