How To Print A List In Python? All The Ways
Lists form an essential part of programming in Python. They look incredibly similar to arrays but offer much more flexibility to the user. In this article, we will briefly discuss what a list is, how it differs from a collection in Python and the various possible ways to print a list in Python.
What are lists?
Python provides lists of container elements to store a collection of similar or different data type items. We declare the elements of a list within square brackets (‘[ elements of list ]’). We can access the list length using the len() function, and they follow 0-indexing just like strings and arrays.
Syntax
The primary declaration of a list follows the following syntax:
<strong>list_var_name = [ element1, element2, ...., elementN ]</strong>
Code language: HTML, XML (xml)
For instance: a = [3, 4, 5]
declares a list containing elements 3, 4, and 5 (all integer data types) stored in the variable a
. You can read more about lists in this Codedamn article.
Arrays v/s Lists
This is a confusion that many beginners may face upfront. Data types allowed in these container elements form the most significant differentiating factor between the two. An array strictly allows all its elements to be the same data type. Any violation of this rule will result in an “Incompatible data types
” error being thrown. Lists, on the other hand, can accommodate data of different types.
For instance: tempList = [1, 2.5, "a"]
is a perfectly valid declaration of a list with different data types elements.
So, lists can have elements with other data types, which traditionally occupy more space than arrays. Arrays also enjoy the benefit of more straightforward numerical computations over lists because of strict data type rules. The choice of one over the other truly depends on the usage and application of the code. For more information regarding how lists fare against arrays, you can visit this Codedamn article.
Different Ways to Print a List in Python
So now that we have got the crux of lists let’s jump into how to print them. We will discuss six methods to print a list. For simplicity’s sake, I will use the same list in all examples.
<strong>listDemo = [1, 2.5, "hello world", True]</strong>
Code language: Python (python)
Let’s get started!
Using the print() method
We can obtain a “raw” output of the list by using the built-in print()
method. This output will contain the quotes around the strings and display the list exactly how you have declared it. You need to pass the list variable name as a parameter to the “print()
” method as follows:
<strong>print(listDemo)</strong>
Code language: Python (python)
Output:
Using a for loop
We can use a for
Loop to iterate over the individual elements of the list and print them. Let’s go over two fun variations of this same way.
Use direct elements in for loop
We can directly use the elements of the list in the for
loop and access them and print them in the order.
<strong>for listItem in listDemo:
print(listItem)</strong>
Code language: Python (python)
Output:
Using index based approach
As we know, lists are 0-index based. That means we can access the first element of the list using the index 0, the second element using index 1, and so on. We can use this property to print the list of items based on their index positions.
<strong>for index in range(len(listDemo)):
print(listDemo[index])</strong>
Code language: Python (python)
Output:
Using the * operator to print the list
We can use the “*
” operator, also known as the “splat” operator, to element-wise print the list. It does so by combining the two approaches we saw above into a single concise command
<strong>print(*listDemo)</strong>
Code language: Python (python)
Output:
Here we can note that the code print(*listDemo)
essentially behaves like the code:
<strong>for listItem in listDemo:
print(listItem, end=' ') </strong>
Code language: Python (python)
Where end=' '
tells the Python interpreter that you need to separate two elements printed by a space, not by the print function’s default newline (\n).
Can you guess what will be the output of this piece of code?
<strong><code>print(*listDemo, sep=', ')</code></strong>
Code language: Python (python)
Yes! You guessed it right. It will be a comma-separated list of elements again displayed on one single line
Output:
Print a List using the map() method
You may have heard the term “map()” come up most popularly along with the trio “map-filter-reduce.” While I won’t digress into the details of those functions, we will talk a bit about map()
them for the sake of the discussion. Python provides us with a built-in method “map()
” that takes two arguments:
- Function: This function will be applied to every element of the list.
- List: The list itself.
So how should we print a list using a function applied over every list element? That’s precisely what is being done when we employ method 2. We will use the print() process and apply this over every component of the list, and in doing so, print out the entire list.
<strong>map(print,listDemo)</strong>
Code language: Python (python)
So, this seems like the correct code but hang on a minute. Why doesn’t it return or print anything? This is so because the map()
function returns a “map object,” which is an iterator of the results obtained after applying the function to each element of the list. Therefore, we need to typecast this object to a list that will unpack the iterator into the individual results.
<strong>list(map(print,listDemo))</strong>
Code language: Python (python)
Output:
Use join() method to print a list
join()
is a string method. As the name suggests, it is used to concatenate multiple strings into one single string. We can use this method as well to print the list. By our intuition, we feel that this should be the correct format:
<strong><code>print(' '.join(listDemo))</code></strong>
Code language: Python (python)
But unfortunately, this throws an error: TypeError: sequence item 0: expected str instance, int found
So why does this happen? This happens because our first item is an integer type, not a string type. So basically, we can derive from this that all the elements need to be of type string for this method to work. We can employ a combination of the previous method along with this one. How would that look?
<strong><code>print(', '.join(list(map(str,listDemo))))</code></strong>
Code language: Python (python)
In this case, we first convert every element to a string using the map() function. Then, we re-converting the iterator object into a list of strings. Finally, we will apply the join() process to concatenate all the individual strings into one long comma-separated string, which the process will print.
Output:
List Comprehension
Python provides a technique called “list comprehension,” which enables us to use expressions inside the declaration of a list. It helps us to create a new list by modifying, filtering, or reducing the elements of an existing list. In our case, the code to print the details of listDemo
using list comprehension will be:
<strong>[print(listItem) for listItem in listDemo]</strong>
Code language: Python (python)
Output:
Conclusion
Phew! That was long, but finally, we are done. Lists form a highly integral part of Python code, and in long development sessions, it can be tough to keep track of issues and debug code. It is then that these printing methods can come in handy. Depending on the situation, you may want to choose one way over another, but I hope I can provide you with a complete reference to gloss over all the methods at hand. Happy Coding!
Sharing is caring
Did you like what Sanchet Sandesh Nagarnaik wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses:
304 students learning
Haris
Python Crash Course for Beginners
Surendra varma Pericherla
Learn Data Structures Using Python