How to Remove Brackets from a List in Python? [8 Methods]

Do you want to erase brackets from a list? In this Python tutorial, I will explain “how to remove brackets from a list in Python” with 8 different methods and techniques.

Removing brackets from a list is the concept of Data Manipulation. I was working on a project as a Data Analyst where I needed to clean some unwanted data. So these 8 methods help me a lot to Remove Brackets from the data.

These are the 8 methods to remove brackets from a list in Python :

  1. Using list comprehension and join
  2. Using str() + list slicing
  3. using strip function
  4. Using replace() method
  5. Using map() and join() methods
  6. using regex
  7. using translate method
  8. Creating a User-defined function

How to remove square brackets from a list Using list comprehension and join in Python

To remove brackets from a list in Python, we are using list comprehension to simplify the code in a line to create a list with conditions. And also using the join() method to concatenate all iterable data into one string.

Let’s take one practical example to understand how to remove brackets from a list in Python using list comprehension with the join() function.

Code

ingredient_list = ['Flour', 'Sugar', 'Eggs', 'Milk', 'Butter']
grocery_list = ', '.join([str(ingredient) for ingredient in ingredient_list])
print("Don't forget to pick up:", grocery_list)

In this code, By iterating over each element in ingredient_list, we are converting it to a string using the str() function in Python.

We are also using the join() method to concatenate these string elements with a comma and space as separators, resulting in a clean and readable representation of the grocery list.

READ:  Python Code to Print a Binary Tree

Output:

Don't forget to pick up: Flour, Sugar, Eggs, Milk, Butter

Attached are snapshots illustrating the Python code and its output in Visual Studio.

How to remove square brackets from list in Python

Remove brackets from a list in Python using str() + list slicing

The str() method of Python is used to convert a value into its string representation, also called typecasting. Also, we are using list slicing to extract the data or to remove the brackets.

Code

test_scores = [5, 6, 8, 9, 10, 21]
print("The original list is:", test_scores)
# Convert the list to a string and remove square brackets
formatted_scores = str(test_scores)[1:-1]
print("List after removing square brackets:", formatted_scores)

Note: This Python program won’t work for nested lists, because it is extracting data from the [1:-1] index.

Output

The original list is: [5, 6, 8, 9, 10, 21]
List after removing square brackets: 5, 6, 8, 9, 10, 21

Here’s a combined view of the Python script and its output within Visual Studio.

Remove Brackets from List in Python

Remove square brackets from a List or a String in Python using the strip() method

The strip() method in Python is used to remove specified characters (whitespace characters by default) from the beginning and end of a string. We’re using this method to remove brackets from a list in Python.

Note: It will not work for nested list brackets.

Here is an example of using the strip() method of Python

Code

employee_names = ["Robert", 'John', 'Ryen', 'Grace', 'Jack']

formatted_names = str(employee_names).strip('[]')
print(formatted_names)

In this code, we’ve converted the whole list to a string and then used the strip(‘[]’) method to remove the unwanted square brackets from the list.

Output

'Robert', 'John', 'Ryen', 'Grace', 'Jack'

Below is the Python code with its output captured in Visual Studio.

Remove square brackets from a List in Python

Remove [] from the list in the python using replace() method

The replace() method is a built-in Python method that replaces all the occurrences inside the string. This method is a direct way to remove all the brackets from the list.

READ:  Calculate exponential value of a number in Python [5 Methods]

It will also work for nested lists in Python, targeting all occurrences we’ve given inside parameters.

Code


tournament_wickets = [5, 6, 8, 9, 10, 21]
print("The original list is : " + str(tournament_wickets))
x=str(tournament_wickets)
x=x.replace("[","")
x=x.replace("]","")
print("List after removing square brackets : " + x)

It converts the list to a string in Python using the str() and replace() methods.

x=str(tournament_wickets)
x=x.replace("[","")
x=x.replace("]","")

We gave parameters as open and closed square brackets to replace them with empty strings in Python.

Output

The original list is : [5, 6, 8, 9, 10, 21]
List after removing square brackets : 5, 6, 8, 9, 10, 21

Presented a screenshot to showcase the Python code and its output in Visual Studio.

How to Print a List Without Brackets in Python

How to erase brackets from the list in Python Using map() and join() methods

The map() is an inbuilt method of Python that is used to apply a function on each element of a list without writing a loop explicitly.

Here is an instance to remove brackets from a list in Python using map() function:

temperatures_fahrenheit = [72, 75, 80, 77, 79, 82]
print("The original list of temperatures is:", temperatures_fahrenheit)

formatted_temperatures = ', '.join(map(str, temperatures_fahrenheit))
print("Formatted temperatures without square brackets:", formatted_temperatures)

In this case, we are using the map() method to apply the str() method in Python on each element of the temperatures_fahrenheit collection.

Output

The original list of temperatures is: [72, 75, 80, 77, 79, 82]
Formatted temperatures without square brackets: 72, 75, 80, 77, 79, 82

Attached is a visual representation of the Python code and its output within Visual Studio.

How to remove brackets from list in Python

Remove brackets from the list using Regex

Regular expressions, or regex, provide a powerful way to search for and manipulate text patterns in strings in Python. We’re using the re.sub() method, this method searches for a pattern in a string and replaces it with another string.

Presented below is a simple example:

import re
order_ids = [101, 102, 103, 104, 105]
# Convert the list to a string and remove square brackets using regular expressions
modified_ids = re.sub(r'[\[\]]', '', str(order_ids))
print(modified_ids)

In this code, re.sub() will search for the square brackets and replace them with the empty string in Python so that it will remove all the square brackets from the string.

re.sub(r'[\[\]]', '', str(order_ids))

Output:

101, 102, 103, 104, 105

Below is a combined screenshot of the Python script and its output in Visual Studio.

Python Remove Square Brackets from a List

Remove square brackets from the list using the translate method in Python

The translate() method in Python replaces characters in a string with other characters or deletes them altogether. It’s particularly useful for replacing multiple characters simultaneously.

READ:  Isdecimal method in Python String

Code


employee_ids = [101, 102, 103, 104, 105]

formatted_ids = str(employee_ids).translate(str.maketrans('', '', '[]'))
print("Formatted employee IDs:", formatted_ids)

This code takes a list of employee IDs and employee_ids and converts it to a string representation using str() in Python.

formatted_ids = str(employee_ids).translate(str.maketrans('', '', '[]'))

Then, it utilizes the translate() method along with str.maketrans(”, ”, ‘[]’) to create a translation table that removes square brackets from the string representation of the list.

Output

Formatted employee IDs: 101, 102, 103, 104, 105

Attached is a merged image displaying the Python code and its output in Visual Studio.

how to return a list without brackets in Python

Creating a User-defined function to delete brackets from the list in Python

We have provided a user-defined function in Python, remove_brackets(), which takes a list as input and converts it into a string representation with elements separated by commas.

Here’s how you can do it:

def remove_brackets(my_list):
    my_string = ""
    for element in my_list:
        my_string += str(element) + ", "
    return my_string
    
li = ['hello', 1, 2,3,"world"]
print(remove_brackets(li))

Output

hello, 1, 2, 3, world

Below is a dual-view screenshot exhibiting the Python code and its output in Visual Studio.

how to erase brackets from the list in Python

Conclusion

Here, we explored eight methods to remove brackets from a list in Python, offering various approaches tailored to different scenarios.

These methods range from utilizing list comprehension and string manipulation techniques to employing built-in functions like strip(), replace(), map(), re.sub(), and the translate() method.

Each method is accompanied by code examples and explanations, demonstrating their effectiveness in simplifying data manipulation tasks.

You may also like to read: