1

I am trying to insert an element into the below list(c5) and obtain new list(c6) when consecutive elements of the list are not same and I have tried below script. This insertion is somehow taking me to infinite loop and I have to kill the program manually to stop the program. Can any one help me to understand this strange behaviour of List in python?

Thanks in advance

c5=['03-03-2017 00:00', '03-03-2017 00:00', '03-03-2017 00:00', '03-03-2017 00:00', '03-03-2017 00:00', '04-03-2017 00:00', '04-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '06-03-2017 00:00', '07-03-2017 00:00', '07-03-2017 00:00', '07-03-2017 00:00', '07-03-2017 00:00', '07-03-2017 00:00', '07-03-2017 00:00', '07-03-2017 00:00', '08-03-2017 00:00', '08-03-2017 00:00', '08-03-2017 00:00', '09-03-2017 00:00', '09-03-2017 00:00', '09-03-2017 00:00', '09-03-2017 00:00', '09-03-2017 00:00', '09-03-2017 00:00', '10-03-2017 00:00']

c6=c5

x=0
for d in c5:
    if(x<(len(c5)-1)):
        if(d != c5[x+1]):
            c6.insert(x+1,'Hurray')
            print(x)
        x+=1

print(c6)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253

1 Answers1

1

c5 and c6 reference the same list object due to:

c6=c5

Iteration through c5 in combination with adding to c6 that references the same list means iterating through a list while you're adding elements to it.

Make c6 a copy by using:

c6 = c5[:]

among other options.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253