This tutorial will discuss multiple ways to remove brackets from a Python list.
Table Of Contents
Remove brackets from List of Lists to create a Flat List
Suppose we have a list of lists. Like this,
sampleList = [[11, 22], [33, 44], [55, 66]]
Now, we want to remove all the square brackets and flatten the list. We can achieve this using list comprehension by iterating over each sublist to create a flattened version. We’ve designed a separate function for this purpose. It takes a nested list as an argument and returns the flattened list.
Essentially, all inner brackets from the list will be removed. We can use this function to flatten a list of lists as demonstrated.
Let’s see the complete example,
def removeBrackets(listObj): # Flattening the list using list comprehension return [item for sublist in listObj for item in sublist] # A List of Lists sampleList = [[11, 22], [33, 44], [55, 66]] print("Original List:", sampleList) # Remove brackets from List of lists to Flatten the List sampleList = removeBrackets(sampleList) print("List after removing brackets:", sampleList)
Output
Frequently Asked:
Original List: [[11, 22], [33, 44], [55, 66]] List after removing brackets: [11, 22, 33, 44, 55, 66]
Remove brackets from List while printing
There might be situations where you wish to display the list elements without brackets while printing. In such cases, you can join all the elements of the list using a comma as a delimiter and then print the result.
This will give the impression that the list elements are displayed on the screen without any square brackets.
Let’s see the complete example,
# A List of Lists sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51] print("Original List:", sampleList) # Join List elements to create a string strValue = ', '.join(map(str, sampleList)) # List Elements after removing brackets print(strValue)
Output
Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51] 45, 67, 22, 45, 22, 89, 71, 22, 51
Summary
Today, we learned about remove brackets from a Python list.