Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+4 votes

if i have a list of aList = [1, 2, 3, 4, 5] and i want to convert it to output "1 2 3 4 5" how do i do that?

i read online that i can convert each item in the list a string and then use .join() but i cant get it to work correctly.. can someone explain this better ?

asked in CSC201 Spring 2021 by (1 point)

2 Answers

+4 votes
Best answer

The syntax for .join() is

<a string to join the list elements with>.join(<list>)

It only works if each element in the list is a string. If the list contains numbers, you might use a for loop to convert each element:

for i in range(len(list)):
    list[i] = str(list[i])
answered by (1 point)
selected by

I would say this is the better approach, since it will work with a list of any length.

(Note, however, that you should NOT name your list variable list, because then if you need to convert something else into a list using the list(...) function, you won't be able to, because you've redefined the identifier list to refer to your list instead of to the list function! Use aList or myList or some other name instead.)

+3 votes

I suggest not to use the .join() method because that will only join a list of strings. I would do this by using the f'string. By indexing each number and putting it into an f'string, so something like this,

f' "{aList[0]} {aList[1]} and so on" '

answered by (1 point)