Python Forum

Full Version: python append
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am stuck on my code,
that's why I coming here because a lot of python master that solve my question...


a = "1,2,3"
ax = a.split(",")

jo = []
for b in ax:
  if b == "1":
    c = "a"
  elif b == "2":
    c = "b"
  elif b == "3":
    c = "c"
  
  jo.append(c)
  print(jo)
and what i get is,

Output:
['a'] ['a', 'b'] ['a', 'b', 'c']
but, the only one output that i want is

Output:
['a', 'b', 'c']
how to fix it?
thank you in advance
Hi, your print statement on line #14 is inside the for loop. That means the line gets executed on each loop run, with intermediate values of "jo". If you only want it to print the final result, place the print statement outside the loop, which will execute it only once - when the loop has finished.
Note that to place it outside the loop, you un-indent it so it has the same indentation as the for statement.
I did this before

a = "1,2,3"
ax = a.split(",")

jo = []
for b in ax:
  if b == "1":
    c = "a"
  elif b == "2":
    c = "b"
  elif b == "3":
    c = "c"
  
jo.append(c)
print(jo)
and it return is

Output:
['c']
but, now i get it..
thanks all, I get what i want now...

a = "1,2,3"
ax = a.split(",")

jo = []
for b in ax:
  if b == "1":
    c = "a"
  elif b == "2":
    c = "b"
  elif b == "3":
    c = "c"
  
  jo.append(c)
print(jo)
Output:
['a', 'b', 'c']
Your print was inside the for loop.
(Aug-31-2017, 07:50 AM)Sagar Wrote: [ -> ]Your print was inside the for loop.

OK, thanks