Concatenate items in a list into a Python string
This post will discuss how to concatenate items present in a Python list into a string separated by a delimiter.
1. Using join() function
To efficiently concatenate items in the list with a preferred delimiter, the recommended solution is to call the join() function on the delimiter, i.e., delim.join(list).
|
1 2 3 4 5 6 |
if __name__ == '__main__': l = ['Python', '3.7'] s = ' '.join(l) print(s) # prints "Python 3.7" |
2. Using reduce() function
Another plausible way to construct a string out of a list is to reduce with a custom function. Here’s a working example:
|
1 2 3 4 5 6 7 8 9 10 11 |
from functools import reduce def concat(x, y): return x + ' ' + y if __name__ == '__main__': l = ['Python', '3.7'] s = reduce(concat, l) print(s) # prints "Python 3.7" |
Here’s another variation that uses lambda expression.
|
1 2 3 4 5 6 7 8 |
from functools import reduce if __name__ == '__main__': l = ['Python', '3.7'] s = reduce(lambda x, y: x + ' ' + y, l) print(s) # prints "Python 3.7" |
That’s all about concatenating items in the list into a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)