Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you join all items in a list?

Tags:

I have a list and it adds each letter of a word one by one to this list, I don't know what will be in the list until the program is run. How do I join each letter in the list into one word? e.g. turn ['p', 'y', 't', 'h', 'o', 'n'] into ['python'].

like image 365
user1790915 Avatar asked Nov 01 '12 09:11

user1790915


People also ask

How do you merge all items in a list python?

The most conventional method to concatenate lists in python is by using the concatenation operator(+). The “+” operator can easily join the whole list behind another list and provide you with the new list as the final output as shown in the below example.

How do you combine all elements in a list into a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

a = ['a', 'b', 'c']
res = "".join(a)

You can again convert back to list of letters using :

list(res)
like image 89
user1305989 Avatar answered Feb 02 '23 01:02

user1305989


''.join(str(v) for v in my_list)

Since you do not know what will be in the list

like image 26
volcano Avatar answered Feb 01 '23 23:02

volcano