-1

I want to add numbers to a pre-existing list and preserve no spacing between comma separated values but when I use the extend function in python, it adds spaces.

Input:

x=[2,3,4]
y=[5,6,7]

Run:

x.extend(y)

Output:

[2, 3, 4, 5, 6, 7]

Desired output:

[2,3,4,5,6,7]

3 Answers3

1

If you don't need to keep its type when printing, You can convert the type of variables with str() and replace whitespaces to ''.

x=[2,3,4]
y=[5,6,7]
x.extend(y)
x_removed_whitespaces = str(x).replace(' ', '')
print(x_removed_whitespaces)

output:

[2,3,4,5,6,7]
0

In Python, lists are printed in that specific way.

>>> x = [2,3,4]
>>> print(x)
>>> [2, 3, 4]

If you want the print function to print the lists in some other way, then you would have to change/override the print method manually, and then specify how you want to print the list. It is explained here.

MaJoR
  • 954
  • 7
  • 20
0

You could write your own function that prints the list the way you want:

def printList(aList):
    print('['+",".join(map(str,aList))+']')

x=[2,3,4]
y=[5,6,7]
x.extend(y)
printList(x)

Output:

[2,3,4,5,6,7]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29