Python concat list elements

How to concatenate all elements of list into string in Python

In this Python tutorial, we will understand the implementation of Python concatenate list to string. Here we will discuss how to concatenate various list elements into a string in Python.

In Python, we can concatenate list elements into a string using the following 5 methods

  • Using for loop & plus (+) operator
  • Using join() method
  • Using join() & list comprehension
  • Using join() & map() function
  • Using reduce() method

Python concatenate list to string

So, in this section, we will discuss all 5 methods to concatenate all list elements to a string in Python.

However, let us first start with the basic method of using the + operator.

Method 1: Python concatenate list to string using for loop & plus (+) operator

In this section, we will discuss the native approach to concatenating a Python list to a string.

Читайте также:  Readonly for html select

So, in this method, first, we will use the for loop to iterate over each item given in the list. After this, we will use the + operator with the string variable and list elements to form a string using it.

Here is an example of this approach in Python.

# Defining a list usa_info = ['The', 'United States', 'is a', 'federal republic', 'consisting of', '50 states'] # Defining a empty string info = '' # Using for loop for element in usa_info: info = info + element + ' ' # Printing final string print(info)

In this example, we have defined a list containing multiple string-type values. After this, we utilized the for loop to iterate over each list element. In the last, we used the + operator to concatenate all the list elements to form a single string.

Here is the final result of the above Python program.

Output: The United States is a federal republic consisting of 50 states

Method 2: UPython concatenate list to string using the join() method

Another way to concatenate a list to a string is by using the join() method in Python. The join() method in Python is a string method that allows joining all the string elements together from a list using a given separator.

Let us see an example where we will concatenate the list elements using the join() method in Python.

# Defining a list usa_info = ['The', 'USA', 'is a country', 'located in', 'North America'] # Using join() to concatenate list to string info = ' '.join(usa_info) # Printing final string print(info)

In this example, we were joining the list elements of the usa_info list using the join() method. However, as a separator, we have used an empty string (” “).

Here is the final result of the above Python program.

Output: The USA is a country located in North America

Method 3: Python concatenate list to string using list comprehension

List comprehension in Python is a concise way to create a new list by performing some operation on each item of an existing Python list.

However, we can use this list comprehension method with the join() method to concatenate all the list elements into a string.

Here is an example of this task in Python.

# Defining a list usa_info = ['The', 'United States', 'is a', 'federal republic', 'consisting of', '50 states'] # Using join() and list comprehension info = ' '.join(str(item) for item in usa_info) # Printing final string print(info)

In the example, we utilized the list comprehension method within the join() method to get each list element. And after this, the join() method will concatenate each element together with an empty space.

After execution, we will get the following result.

Output: The United States is a federal republic consisting of 50 states

Method 4: Python concatenate list to string using the map() function

The map() is a built-in Python function that allows to execute a particular function on each element of a given iterable.

So, by using the map() function, we will convert each list element to a string data type. And then we will use the join() method to concatenate all the elements to form a single string.

# Defining a list usa_info = ['The', 'USA', 'is a country', 'located in', 'North America'] # Using join() & map() to concatenate list to string info = ' '.join(map(str, usa_info)) # Printing final string print(info)

In the example, we converted the usa_info list elements to string using the map() function. After this, we used the join() method to concatenate all list elements to a string in Python.

Here is the result of the above Python program.

Output: The USA is a country located in North America

Method 5: Python concatenate list to string using reduce() method

The reduce() is a built-in Python function that is available in the functools module. This function enables us to apply binary functions to each element of an iterable resulting in reducing the result to a single value.

Here is a method to use the reduce() function with lambda and form a single string as a result.

# Importing reduce() method from functools import reduce # Defining a list usa_info = ['America', 'is often', 'used as a', 'shorthand term', 'for the', 'USA'] # Using reduce() to concatenate list to string info = reduce(lambda element_x, element_y: element_x + ' ' + element_y, usa_info) # Printing final string print(info)

In the example, we utilized the reduce() function to concatenate list elements of the usa_info list to the info string.

Once the above Python program is executed, we will get the following result.

Python concatenate list to string

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how Python concatenate list to string using 5 different methods. Moreover, we have also covered examples related to each method in Python.

Here is the list of methods that we discussed.

  • Using for loop & plus (+) operator
  • Using join() method
  • Using join() & list comprehension
  • Using join() & map() function
  • Using reduce() method

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

6 Ways to Concatenate Lists in Python

6 Ways to Concatenate Lists in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

  • concatenation (+) operator
  • Naive Method
  • List Comprehension
  • extend() method
  • ‘*’ operator
  • itertools.chain() method

1. Concatenation operator (+) for List Concatenation

The ‘+’ operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list1 + list2 print ("Concatenated list:\n" + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

2. Naive Method for List Concatenation

In the Naive method, a for loop is used to traverse the second list. After this, the elements from the second list get appended to the first list. The first list results out to be the concatenation of the first and the second list.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("List1 before Concatenation:\n" + str(list1)) for x in list2 : list1.append(x) print ("Concatenated list i.e. list1 after concatenation:\n" + str(list1)) 
List1 before Concatenation: [10, 11, 12, 13, 14] Concatenated list i.e. list1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

3. List Comprehension to concatenate lists

Python List Comprehension is an alternative method to concatenate two lists in Python. List Comprehension is basically the process of building/generating a list of elements based on an existing list.

It uses for loop to process and traverses the list in an element-wise fashion. The below inline for-loop is equivalent to a nested for loop.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [j for i in [list1, list2] for j in i] print ("Concatenated list:\n"+ str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

4.Python extend() method for List Concatenation

Python’s extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print("list1 before concatenation:\n" + str(list1)) list1.extend(list2) print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1)) 

All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

list1 before concatenation: [10, 11, 12, 13, 14] Concatenated list i.e ,ist1 after concatenation: [10, 11, 12, 13, 14, 20, 30, 42] 

5. Python ‘*’ operator for List Concatenation

Python’s ‘*’ operator can be used to easily concatenate two lists in Python.

The ‘*’ operator in Python basically unpacks the collection of items at the index arguments.

For example: Consider a list my_list = [1, 2, 3, 4].

The statement *my_list would replace the list with its elements at the index positions. Thus, it unpacks the items of the lists.

list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [*list1, *list2] print ("Concatenated list:\n " + str(res)) 

In the above snippet of code, the statement res = [*list1, *list2] replaces the list1 and list2 with the items in the given order i.e. elements of list1 after elements of list2. This performs concatenation and results in the below output.

Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

6. Python itertools.chain() method to concatenate lists

Python itertools modules’ itertools.chain() function can also be used to concatenate lists in Python.

The itertools.chain() function accepts different iterables such as lists, string, tuples, etc as parameters and gives a sequence of them as output.

It results out to be a linear sequence. The data type of the elements doesn’t affect the functioning of the chain() method.

For example: The statement itertools.chain([1, 2], [‘John’, ‘Bunny’]) would produce the following output: 1 2 John Bunny

import itertools list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list(itertools.chain(list1, list2)) print ("Concatenated list:\n " + str(res)) 
Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] 

Conclusion

Thus, in this article, we have understood and implemented different ways of Concatenating lists in Python.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью