Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Remove Square Brackets from a List using Python
Python lists are displayed with square brackets by default when printed. Sometimes you need to display list contents without these brackets for better formatting or presentation purposes. This article covers six different methods to remove square brackets from Python lists.
Method 1: Using str() and replace()
The simplest approach is to convert the list to a string and replace the bracket characters with empty strings
# List containing elements
names = ["Jack", "Harry", "Sam", "Daniel", "John"]
# Convert to string and remove brackets
result = str(names).replace('[', '').replace(']', '')
print(result)
'Jack', 'Harry', 'Sam', 'Daniel', 'John'
Method 2: Using List Comprehension with join()
This method converts each element to a string and joins them with a separator
# List with elements letters = ['A', 'B', 'C', 'D', 'E'] # Join elements with comma and space result = ', '.join([str(element) for element in letters]) print(result)
A, B, C, D, E
Method 3: Using map() with join()
The map() function applies str() to each element, then join() combines them
# List with numbers numbers = [1, 2, 3, 4, 5] # Convert to strings and join result = ', '.join(map(str, numbers)) print(result)
1, 2, 3, 4, 5
Method 4: Using strip()
Convert the list to string and strip the first and last bracket characters
# List with elements
items = ['P', 'Q', 'R', 'S', 'T']
# Convert to string and strip brackets
result = str(items).strip('[]')
print(result)
'P', 'Q', 'R', 'S', 'T'
Method 5: Using re Module
Regular expressions can match and replace bracket patterns
import re # List with numbers data = [1, 2, 3, 4, 5] # Remove brackets using regex result = re.sub(r'[\[\]]', '', str(data)) print(result)
1, 2, 3, 4, 5
Method 6: Using translate()
Create a translation table to remove specific characters
# List with numbers
values = [1, 2, 3, 4, 5]
# Create translation table and remove brackets
result = str(values).translate(str.maketrans('', '', '[]'))
print(result)
1, 2, 3, 4, 5
Comparison
| Method | Best For | Readability | Performance |
|---|---|---|---|
join() with comprehension |
Clean formatting | High | Fast |
map() with join()
|
Functional programming | High | Fast |
replace() |
Quick solutions | Medium | Medium |
strip() |
Simple lists | High | Fast |
re.sub() |
Complex patterns | Low | Slower |
translate() |
Character removal | Low | Fast |
Conclusion
Use join() with list comprehension or map() for clean, readable output formatting. For simple bracket removal from string representations, strip() or replace() work well. Choose the method that best fits your specific use case and coding style.
