Home > OS >  How do I remove a trailing comma on an array list on Python?
How do I remove a trailing comma on an array list on Python?

Time:10-05

I hope you had a great day today. I have some difficulties implementing commas into my code so that the list of numbers is displayed nicely. Here is my code. Any suggestions and advice are appreciated.

from random import randint
def randomIntegers(): 
    numbers = []
    for i in range(10):
        numbers.append(randint(1, 100)) #Range of random numbers goes up to 100.
    print(f"The numbers are: {numbers}")

    print("The elements of the list at an even index are: ", end=' ')
    for i in range(10):
        if i % 2 == 0: 
            print(numbers[i], end=' ')

    print("\nThe even elements in the list are: ", end=' ')
    for i in range(10):
        if numbers[i] % 2 == 0: 
            print(numbers[i], end=' ') 

    print("\nAll the elements in reverse order are: ", end=' ')
    for i in range(9, -1, -1): 
        print(numbers[i], end=' ')  

    print(f"\nThe first element is {numbers[0]} and last element is {numbers[-1]}.")
randomIntegers()

I would like to have my output of random numbers be like this "All the elements in reverse order are 16, 67, 31, 46, 12, 7, 70, 92, 98, 67" instead of having the comma at the end.

CodePudding user response:

As flakes commented, the str.join() method joins the iterable passed to it by the string str. For example, '-'.join([1,2,3,4,5]) returns the string '1-2-3-4-5'.

CodePudding user response:

Here's a simpler version of your code using list comprehension and joins. When testing, I found that joins on int lists needed to be cast to strings when joining. For some reason its not implied in the interpreter, but alas.

from random import randint
def randomIntegers(): 
    numbers = [randint(1, 100) for i in range(10)]
    print(f"The numbers are: {numbers}")

    print("The elements of the list at an even index are: "   ", ".join([str(numbers[i]) for i in range(10) if i % 2 == 0]))

    print("The even elements in the list are: "   ", ".join([str(n) for n in numbers if n % 2 == 0]))

    print("All the elements in reverse order are: "   ", ".join([str(n) for n in reversed(numbers)]))

    print(f"The first element is {numbers[0]} and last element is {numbers[-1]}.")
randomIntegers()
  • Related