Home > OS >  Why an element is not printing?
Why an element is not printing?

Time:10-19

I am learning the list and list assignments and using while and for loops with lists. I wrote the following code just to test my understanding.

I=[1,4, 7, 6, 7,8,9]
IU=I

while IU !=[]:
    print ('I: ',I)
    print('IU :' ,IU)
    for i in I:
        print(i)
        if i*i<=36:
            IU.remove(i)
            print(IU)
    if i>=9:
        break 

This gives the following output:

I:  [1, 4, 7, 6, 7, 8, 9]
IU : [1, 4, 7, 6, 7, 8, 9]
1
[4, 7, 6, 7, 8, 9]
7
6
[4, 7, 7, 8, 9]
8
9

My understanding is that it would print 4 after it removed 1 from IU. However it is not printing 4. Any hints on why this is happening?

CodePudding user response:

Issue

The issued line is IU=I

This line does not create a new list IU. Python creates a reference 'IU' to the original list I, which means IU and I point to the same list. Thus, when you remove 4 from your I, IU get affected too.

Solution

There are different ways of copying of I. For example, you can

IU = [_ for _ in I]

Or

IU = I.copy()

demo

Here is a demo show the difference

L = [1,2]
Ref = L
Cpy = L.copy()

L.append(3)
print(Ref)
print(Cpy)
  • Output

    [1, 2, 3]
    [1, 2] 
    

CodePudding user response:

You don't see 4 printed because when the program removed 1 initially, the loop pointer i was pointing to 1, and so, once 1 got removed, the i pointer moved to the next element, 4. And at the end of the loop, since the for loop goes over to the next element (i that we do in c ), it points at 7 at the starting of next iteration. Hope I could solve your doubt.

CodePudding user response:

List in python is implemented using Dynamic Array

Here, after the removal of 1 from the list, the list on the left moves backward(not exactly but somewhat similar), so i now points to 4.

Now i gets incremented, thus now i points to the next memory location.

Please check the link to see how the list gets implemented inside python.

  • Related