0

I'm confused by the following code:

lst = ['1','2','3']
s = [str(i) for i in lst]
print(s)

and

lst = ['1','2','3']
for i in lst:
    s = [str(i)]
print(s)

Why does the first one print out ['1','2','3'] but the second one only print out ['3']? Also, how can I print out ['1','2','3'] with the "normal form" of a for-loop like the second one (because I don't understand how the first one works).

martineau
  • 119,623
  • 25
  • 170
  • 301
Kim Gordon
  • 31
  • 6
  • s is overwritten in every iteration in the second code – Sayse Jul 14 '21 at 10:17
  • In the first example the code first makes the list and then assigns it to s. In the second example s is being overwritten each time. If you want it to work in the second section you would need to create s before the for loop e.g.: s= [] for i in lst: s.append(str(i)) – bio_dan Jul 14 '21 at 10:18
  • Strongly suggest you become familiar with the second form and how it works since it's a very useful, powerful, and common Python idiom. – martineau Jul 14 '21 at 10:48

0 Answers0