Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does it only change the last string in the list? (For-loop) python

a =['10-Sep-12','11-Sep-12','12-Sep-12','13-Sep-12','14-Sep-12','15-Sep-12','16-Sep-12','17- Sep-12','18-Sep-12','19-Sep-12','20-Sep-12','21-Sep-12','22-Sep-12','23-Sep-12']

for i in range (len(a)):
   date = datetime.strptime(a[i], "%d-%b-%y")

Why this code only change datetime format for the last string of the list only?

print (date)
Output : 2012-09-23 00:00:00

How can I fix this code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are printing date outside the for loop that’s why you are getting the only the last value.

Do this and you’ll see that each string got converted to datetime.

a =['10-Sep-12','11-Sep-12','12-Sep-12','13-Sep-12','14-Sep-12','15-Sep-12','16-Sep-12','17-Sep-12','18-Sep-12','19-Sep-12','20-Sep-12','21-Sep-12','22-Sep-12','23-Sep-12']

for i in range (len(a)):
  date = datetime.strptime(a[i], "%d-%b-%y")
  print(date)

Whenever you run a loop the value of the variable changes each iteration. If you print that variable outside the loop, it’ll only print the last value of the variable. In your case being the value stored inside it in the 14th iteration.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading