Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python append
#1
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
Reply
#2
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.
Reply
#3
Note that to place it outside the loop, you un-indent it so it has the same indentation as the for statement.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
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']
Reply
#5
Your print was inside the for loop.
Reply
#6
(Aug-31-2017, 07:50 AM)Sagar Wrote: Your print was inside the for loop.

OK, thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  why is the append function gets empty on the loop?/python rhai 3 3,147 Jul-07-2018, 12:19 PM
Last Post: rhai

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020