- How to Print a List Without Square Brackets in Python
- 1) Use for loop to print a list without brackets or commas
- 2) Use the Join() Function to print an array without square brackets or commas
- 3) Use the Asterisk ‘*’ operator to print a list without square brackets
- 4) Use List Comprehension
- Python Print List without Brackets
- 1. Quick Examples of Displaying Lists without Brackets
- 2. Print Lists without Brackets
- 3. Use Join to Print List without Brackets
- 4. Print List Comprehension
- 5. Using str() Function
- 6. Conclusion
- You may also like reading:
- Printing a list of lists, without brackets
- 6 Answers 6
- Python: Printing a list without the brackets and single quotes?
- 2 Answers 2
How to Print a List Without Square Brackets in Python
This tutorial is about How to Print a List without Square Brackets in Python. We are assuming that you’re familiar with the basic concepts of lists. There are various techniques to print lists without showing square brackets which are explained below in detail.
To Print a list without Square Brackets in Python, you can use for loop, join() Functions, and asterisk ‘*’ operator. Using for loop, traverse through list elements one by one and print them with commas in between them.
1) Use for loop to print a list without brackets or commas
One of the simplest methods that come to mind is to print the list elements using for loop. Using for loop, traverse through list elements one by one and print them with commas in between them. For example:
fruits = ["Apple", "Mango", "Orange", "Guava", "Peach"] for item in fruits: print(item, end=" ")
Apple Mango Orange Guava Peach
In the code snippet shown above, the for loop iterates and prints item of lists on every iteration. The end argument inserts space after each element. You can also separate all items with commas or any other character by specifying it in the end argument.
2) Use the Join() Function to print an array without square brackets or commas
The join() function takes an iterable object such as a list, tuple, dictionary, string, or set as an argument and returns a string in which all the elements are joined by a character specified with the function. For example: Suppose you have a list consisting of the name of fruits as an element and you want to print the elements of the list. We can join these names of fruits with commas between them using the join method.
fruits = ['apple','mango','banana','gauva'] print(', '.join(fruits))
Similarly, if we replace the comma in the above example with a space, then the above code will print the names of fruits separated with a space between them instead of commas.
fruits = ['apple','mango','banana','gauva'] print(' '.join(fruits))
This method only works with a list of strings and will fail if the list contains integer or float values. For lists containing integers, first, convert the list into the string using the map() function then use the join function. The map() function takes two arguments a function and an iterable. It maps all the items of the iterable to the specified function mentioned in the first argument.
list1 = [1,2,3,4,5,6,7,8,9,10] print(', '.join(map(str, list1)))
In the above example, the map() function converts all the items of the list into a string datatype which is then joined with commas between them.
3) Use the Asterisk ‘*’ operator to print a list without square brackets
To print a list without square brackets in Python, there are multiple techniques available. One approach is to use the asterisk (*) operator. The asterisk operator can be used to unpack the elements of a list and print them without the square brackets. You can unpack list elements using an asterisk(*) operator. This operator is used to unpack elements of iterable objects. As a list is also an iterable object, therefore we can unpack list elements using this operator and print them without the square brackets. For example
fruits = ['apple','mango','banana','gauva'] print(*fruits, sep = ' ')
This method works for lists containing strings, integers, or floating-point numbers. You can also specify a delimiter by passing it as the ‘sep’ argument. Additionally, list comprehension, the join() function, and the str() function can be used for printing lists without square brackets in Python.”
list1 = [1,2,3,4,5,6,7,8,9,10] print(*list1, sep = ', ')
4) Use List Comprehension
List Comprehension can also be used to print the numbers without square brackets in Python.
In this example, the list comprehension [str(num) for num in numbers] creates a new list where each element of the numbers list is converted to a string. The resulting list is [‘1’, ‘2’, ‘3’, ‘4’, ‘5’] .
Then, the join() method is used to concatenate the elements of the new list with a comma and a space as the delimiter, resulting in the string “1, 2, 3, 4, 5”. Finally, the concatenated string is printed without the square brackets.
numbers = [1, 2, 3, 4, 5] # Create a new list comprehension to convert each element to a string numbers_str = [str(num) for num in numbers] # Use the join() method to concatenate the elements with a delimiter result = ", ".join(numbers_str) # Print the resulting string without square brackets print(result)
Python Print List without Brackets
How to print the list without square brackets? When you display the lists by default it displays with square brackets, sometimes you would be required to display the list or array in a single line without the square brackets []. There are multiple ways to achieve this. For example using * operator, join(), list comprehension e.t.c
1. Quick Examples of Displaying Lists without Brackets
Following are quick examples of how to display a list without brackets.
# Quick examples of printing lists without brackets # Print list with space separator & without brackets print(*numbers) # Print with comma separator & without brackets print(*numbers, sep = ",") # Printing numbers as a string print(' '.join(map(str, numbers))) # Using list comprehension [print(i, end=' ') for i in numbers]
2. Print Lists without Brackets
We can use the * operator to print elements of the list without square brackets and with a space separator. You can also use this to display with comma, tab, or any other delimiter.
# Create Numbers List numbers = [11,12,13,14,15,16,17] print(numbers) # Using * Operator # Print list with space separator print(*numbers) # Print comma separator print(*numbers, sep = ",") # Print comma with additional space print(*numbers, sep = ", ")
Yields below output. Here, the star(*) unpacks the list and returns every element in the list.
3. Use Join to Print List without Brackets
If you wanted to print the list as a string without square brackets, you can use the join() to combine the elements into a single string. The join() can be used only with strings hence, I used map() to convert the number to a string.
In the second example, I used the list of strings hence map() was not used.
# Create Numbers List numbers = [11,12,13,14,15,16,17] # Printing numbers as a string print(' '.join(map(str, numbers))) # Output: # 11 12 13 14 15 16 17 # Printing string as a single string mylist = ['Apple','Mango','Guava','Grape'] mystring = ' '.join(mylist) print(mystring) # Output: #Apple Mango Guava Grape
4. Print List Comprehension
You can also use list comprehension to display the list in a single line without square brackets. Here, for is used to get one element at a time from the list, and print() is used to display the element.
# Using list comprehension [print(i, end=' ') for i in numbers] # Output: #11 12 13 14 15 16 17
5. Using str() Function
The str() function converts the numbers list to a string with square brackets and each element is separated by space. To remove the brackets use [1:-1], meaning remove the first and last character from the string.
# Using str() print(str(numbers)[1:-1]) # Output: #11 12 13 14 15 16 17
6. Conclusion
In this article, you have learned different ways to print lists in Python without brackets. Learned to use * operator, print a list as a string, using list comprehension.
You may also like reading:
Printing a list of lists, without brackets
A somewhat similar question was asked on here but the answers did not help. I have a list of lists, specifically something like..
[[tables, 1, 2], [ladders, 2, 5], [chairs, 2]]
tables 1, 2 ladders 2, 5 chairs 2
tables 1 2 ladders 2 5 chairs 2
But that isn’t quite close enough. Is there a simple way to do what I’m asking? This is not meant to be the hard part of the program.
6 Answers 6
for item in l: print item[0], ', '.join(map(str, item[1:]))
For your input, this prints out
tables 1, 2 ladders 2, 5 chairs 2
@LarryLustig: As far as I can see, the output is exactly as the OP requested, down to spaces and commas.
I just tried this with: [[‘wind’, 1, 2], [‘blow’, 1], [‘form’, 1], [‘south’, 1], [‘strong’, 2]] I got output of: w i, n, d Followed by a traceback error about why an int is not subscriptable
@user1079404: I’ve just tested the code on your list and it works. Make sure you’re applying it to the entire list, not to each element.
Sorry, I see what I was doing wrong. The code works fine, but, I don’t understand is the way that «join» works, so it always adds the string (in this case ‘, ‘) on to the end of each string in the iteration?
@user1079404: It inserts the , between consecutive elements. See docs.python.org/library/stdtypes.html#str.join
If you don’t mind that the output is on separate lines:
foo = [["tables", 1, 2], ["ladders", 2, 5], ["chairs", 2]] for table in foo: print "%s %s" %(table[0],", ".join(map(str,table[1:])))
To get this all on the same line makes it slightly more difficult:
import sys foo = [["tables", 1, 2], ["ladders", 2, 5], ["chairs", 2]] for table in foo: sys.stdout.write("%s %s " %(table[0],", ".join(map(str,table[1:])))) print
Also, it’s possible to use end=» as a parameter in print function as of Python 3, or in Python 2 with adding from __future__ import print_function statement at the beginning.
for item in l: print(str(item[0:])[1:-1])
For your input, this prints out:
tables 1, 2 ladders 2, 5 chairs 2
Another (cleaner) way would be something like this:
for item in l: value_set = str(item[0:]) print (value_set[1:-1])
tables 1, 2 ladders 2, 5 chairs 2
Hope this helps anyone that may come across this issue.
L = [['tables', 1, 2], ['ladders', 2, 5], ['chairs', 2]] for el in L: print(' '.format(el[0],', '.join(str(i) for i in el[1:])))
tables 1, 2 ladders 2, 5 chairs 2
is the output string where
is equal to el[0] which is ‘tables’ , ‘ladders’ , .
is equal to ‘, ‘.join(str(i) for i in el[1:])
and ‘, ‘.join(str(i) for i in el[1:]) joins each element in the list from these: [1,2] , [2,5] . with ‘, ‘ as a divider.
str(i) for i in el[1:] is used to convert each integer to string before joining.
This pretty much makes sense, thank you for the explinations, but it also comes up with the same strange output that I responded to the first answer does. It will print something like: [[‘wind’, 1, 2], [‘blow’, 1], [‘form’, 1], [‘south’, 1], [‘strong’, 2]] I got output of: w i, n, d Followed by a traceback error about why an int is not subscriptable
Python: Printing a list without the brackets and single quotes?
I have a list full of IP addresses. I would like to iterate through the list and print each IP address. When I try doing this:
def printList(theList): for item in theList: print item
['8.0.226.5'] ['8.0.247.5'] ['8.0.247.71'] ['8.0.249.28'] ['8.0.249.29']
@Dan: One list you’re trying to take the item with index 0 from must be empty. I see that what you printed is not empty, but index 0 is only out of range when there isn’t a (0+1)th item, i.e. when the list is empty, so if you get that error there must be an empty list, period. Show the code and exampel data ( print repr(theList) should give you an exact representation of the list) that causes the error (e.g. on pastebin.com).
2 Answers 2
Each item in the list is itself a singleton list. There’s propably no reason for this — if you can’t name one, go and remove them (by using re.find over re.findall or returning a single item from the list returned by re.findall ), they’re just redundant and cause trouble like in this case.
Regardless, print item[0] should work as it’s printing the single element in the list, and unlike the str() of lists, it won’t run the item through repr first (which causes the quotes and would escape unprintable characters if there were any in the string). And once you got rid of the redundant singleton lists, print ‘\n’.join(items) will work as well.
Your code throws an error if there is an empty list in theList . If there is a line in recentFile that does not contain anything formatted like an IP, an empty list will be returned by returnIP , and if any line in comparisonFile (by the way: you open it with a descriptive name at the beginning, but open it again and again without a descriptive name in chechMatch ) contains no IP address either, you’ll get another empty list which of course equals the empty list passed as parameter ip . So for non-IP names in recentFile , empty lists will be added. This whole troubel can be avoided if you return strings instead of singleton lists from returnIP , use None when there is no IP in the current line, and skip the checking/appending in compareFiles if returnIP returns None .