How to print an integer vector by removing the last comma in Python 3?

Asked

Viewed 2,822 times

3

I want to print on the screen an array of integer numbers in the same line and separated by comma, and I want to remove the comma that is after the last number.

How could I do that in Python?

My code is like this:

for i in range(12):
    print(numeros[i],end=",")

2 answers

3

Python has this idea of having a way that is the obvious way to solve things - but not always the obvious is so obvious at first glance. This problem always gets ugly in other languages, just because you have to leave a special case for the last element.

So, in the case of a sequence that you don’t know the length beforehand, (for example, if you’re reading from a file) in other languages you may have to use an auxiliary variable to know if it’s the first interaction, but print the "," at the beginning of the loop:

primeiro = True
for i in sequencia:
    if not primeiro:
        print(", ", end="")
        primeiro = False
    print(i)
print()

If the sequence has known length, such as a list, you can do an "if" and not print ", " to the last element.

In Python, strings have the method join which is very interesting: it concatenates strings from a sequence using the initial string as a separator. So he never prints the separator either at the beginning or at the end of a sequence.

So if I have:

a = ["Universidade", "de", "Campinas"]
b = " ".join(a)
print(b)

Will display

University of Campinas

The only problem is that being a string method, "Join" expects all elements of the sequence that will concatenate to be themselves strings.

Then comes another element of Python - the language has a syntactic way to solve in a synthetic way everything that solves repetition (and filters) of a sequence - the so-called "mapping and filtering" problems: you use a for as part of an expression: you put first the expression you want to use to transform all elements of the sequence, and then type "for" - for example:

(elemento * 2 for elemento in sequencia)

It would result in an iterator that delivers each element of the initial "sequence" multiplied by 2.

So, since we want all the elements of the number array transformed into a string before calling "Join", just do:

print(", ".join(str(i) for i in range(12)))

To make your impression of the elements interspersed with ", ".

(Note that there is a difference if the "for" of an expression is placed between brackets ([x for x in y])- this always generates a list, with all the elements in memory - without the additional brackets, you have a generator which can be used only once, except that the elements are computed as they are used and are never stored all in memory. For an immediate flame to join it makes no difference).

3


In a way Pythonico it is possible to concatenate the list elements into a string separated by a comma. The map serves to convert list values (created by range()) for string.

numeros = ','.join(map(str, range(12))) 
print(numeros)

Or maybe so, doing the conversion to string using comprehensilist on:

numeros = ','.join([str(x) for x in range(12)])
print(numeros)

It is also possible to make a if. This is a approach least Pythonic, but it’s much simpler to understand, especially if you’re learning.

for i in range(12):
    if(i != 11):
        print(i, end=",")
    else: 
        print(i)
  • For aesthetic questions (exhibition only), it would be possible to do only print(str(numeros)[1:-1]). If the return is used for anything else, use join.

  • Thanks! I decided to use your first suggestion to solve my problem.

  • 1

    guy - the approache "less pythonic" is not "much simpler". Join with genertor Expression is the right way to do this (but not with map, map really breaks readability).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.