-3

instead of printing 12359 it prints 9 for some reason

code

  b=["12","3","5","9"]
  b1=[]
  for x in range(0,len(b)):
      b1=b[x]

  print(b1,end='')

output

9
  • You have to indent print(b1) as well, so it will be executed in the loop. This will print every number in a single line though. If you want to have them all in one line, you will to add them to an output string. – Honn Feb 19 '21 at 13:43
  • I am new to python so i dont understand what you meant – THE MISSING LINK Feb 19 '21 at 13:45
  • Everything with the same indent (number of spaces before the code) as `b1=b[x]` will get executed inside the loop. To create a list or string, see my more detailed answer. – Honn Feb 19 '21 at 13:47
  • Does this answer your question? [List append() in for loop](https://stackoverflow.com/questions/41452819/list-append-in-for-loop) – costaparas Feb 19 '21 at 13:47

3 Answers3

2

Well, if you want to concatenate the elements of b into a string, just try:

b = ["12", "3", "5", "9"]
b1 = ''.join(b)

Explanation:

Help on built-in function join:

join(iterable, /) method of builtins.str instance
    Concatenate any number of strings.
    
    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.
    
    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
Luca Sans S
  • 122
  • 8
1

If you want to concatenate all strings, you need to use a string for b1:

b = ["12", "3", "5", "9"]
b1 = ""
for x in range(0, len(b)):
    b1 += b[x]
print(b1)
jo3rn
  • 1,166
  • 1
  • 9
  • 26
0

b1 is not a list. Its is a string. If you to have a list, do this:

 b=["12","3","5","9"]
  b1=[]
  for x in range(0,len(b)):
      b1.append(b[x])

print(b1) # Prints the exact same as b.

If you want an output string, you should add it to an empty string like so:

 b=["12","3","5","9"]
  b1=""
  for x in range(0,len(b)):
      b1 += b[x]
Honn
  • 646
  • 1
  • 15