- Printing a List in Python – 10 Tips and Tricks
- 10+ Ways to Print a List in Python
- 1. Print a list using *
- 2. Print a List in One Line
- 3. Print a Python List With a Separator Between Items
- 4. Print a List in Python Without a Separator at the End
- 5. Print a Python List Using join
- 6. Convert and Print a List
- 7. Print and Index a Python List
- 8. Print Two Python Lists Together
- 9. Print a Nested Python List
- 10+. There’s Always More …
- Beyond Printing Lists in Python
- Python Program to display elements of an array
- How to display the elements of an array in python?
- ALGORITHM
- Python Source Code
- OUTPUT
Printing a List in Python – 10 Tips and Tricks
The Python print() function is an essential built-in function, and it is important to use alongside Python lists.
To learn how a Python list works, what kind of data structure it is, and why it is essential to Python and programming in general, it’s best to take our Python Data Structure course. It has 118 interactive exercises, and you only need a web browser and some basic Python knowledge. When you finish it, you’ll understand lists, tuples, sets, and dictionaries in Python.
If you already have some knowledge of Python data structures, here are some tips and tricks on how to print a list in Python.
10+ Ways to Print a List in Python
1. Print a list using *
To print a list using the * operator, you can use the print() function as follows:
This will print the elements of the list separated by spaces, just like when you use the print() function with multiple arguments. For example:
pokemon_list = ['Pikachu', 'Abra', 'Charmander'] print(*pokemon_list)
You can also use the * operator to unpack a list when calling a function that takes multiple arguments:
def print_pokemon(pokemon1, pokemon2, pokemon3): print(pokemon1) print(pokemon2) print(pokemon3) print_pokemon(*pokemon_list)
2. Print a List in One Line
It is also possible to print a list in one line of code using this syntax:
print(item for item in list_name)
To do so, you can use a generator expression inside the print() function.
A generator expression is similar to a list comprehension, but it returns a generator object that produces the values one at a time (instead of creating a new list). Generator expressions and list comprehensions are Python one-liners – i.e. they are one-line Python programs.
Here’s an example of how you can use a generator expression to print a Python list:
pokemon_list = ['Pikachu', 'Abra', 'Charmander']
This will print the elements of the list separated by spaces, just like when you use the print() function with multiple arguments:
You can also use a generator expression to unpack a list when calling a function that takes multiple arguments. For example:
def print_pokemon(pokemon1, pokemon2, pokemon3): print(pokemon1) print(pokemon2) print(pokemon3) print_pokemon(*(item for item in pokemon_list))
Keep in mind that generator expressions are usually used when you only need to iterate over the values once; they are not stored in memory like lists are. If you need to access the values of the list multiple times, it might be more efficient to use a list comprehension or to store the values in a list.
3. Print a Python List With a Separator Between Items
To print a list with a separator between list items, you can use a list comprehension inside a print() function:
print(*[item + '\n' for item in pokemon_list])
The newline character \n at the end of each element ensures each element will print on a separate line:
Remember that you can use any string as a separator, not just a newline character. For example, to print a list in Python with a comma and a space between each element, you can use the following syntax:
print(*[item + ', ' for item in pokemon_list])
Note that the last element will have a comma and a space after it, which might differ from what you want.
4. Print a List in Python Without a Separator at the End
To avoid this pitfall, you can use an if statement inside a list comprehension to only add the separator after the elements that are not last in the list. Here’s how it looks:
To print a list with a separator between the list items but without the separator at the end, you can also use the print() function with the sep keyword argument:
This will print the elements separated by a comma and a space:
Note that the print() function automatically adds a space after each element, so you don’t need to include it in the separator string.
Similar to what I mentioned previously, you can use any string as a separator, such as a dash:
Remember that the sep keyword argument only affects the separator between elements, not the characters printed after the last element.
Suppose you want to suppress the space automatically added after the last element. In that case, you can use the end keyword argument to specify a different string to be printed after the last one:
print(*pokemon_list, sep=', ', end='')
5. Print a Python List Using join
To print a list using the join() method in Python, you can use the following syntax:
print(separator.join(list_name))
This will join the list elements with the separator string between them. For example, to print a list of pokemons separated by a comma and a space, you can do the following:
If you want to add a string before or after the list, you can use the + operator to concatenate the strings:
print('Pokemons: ' + ', '.join(pokemon_list))
Pokemons: Pikachu, Abra, Charmander
6. Convert and Print a List
To print a list by converting it to a string in Python, you can use the str() function:
This will print the list as a string, with the elements separated by commas and enclosed in square brackets:
Next, let’s explore how to print a Python list while indexing the list elements.
7. Print and Index a Python List
To print the items of a list with their index, you can use the Python function enumerate() with a for loop:
for i, pokemon in enumerate(pokemon_list): print(i, pokemon)
0 Pikachu 1 Abra 2 Charmander
The enumerate() function returns an iterator that produces tuples containing the index and the value of each element of the list. You can use a for loop to iterate over these tuples and print the index and value of each element.
Using a variation of the previous way we did string formatting, we can customize how the index and value are printed. For example:
for i, pokemon in enumerate(pokemon_list): print('<>: <>'.format(i, pokemon))
0: Pikachu 1: Abra 2: Charmander
You can also use a list comprehension to create a new list of strings with the formatted index and value of each element and then use the print() function to print the list:
result = ['<>: <>'.format(i, pokemon) for i, pokemon in enumerate(pokemon_list)] print(result)
['0: Pikachu', '1: Abra', '2: Charmander']
Remember that the enumerate() function returns the index of each element starting from 0. If you want the index to start from a different value, you can pass it as a function argument. For example:
for i, pokemon in enumerate(pokemon_list, 1): print('<>: <>'.format(i, pokemon))
1: Pikachu 2: Abra 3: Charmander
8. Print Two Python Lists Together
To print two lists together, with the elements of each list interleaved, you need to loop over multiple lists. For this purpose, you can use a for loop and the zip() function.
The zip() function returns an iterator that produces tuples containing the elements at their corresponding positions inside the list. You can use a Python loop to iterate over these tuples and print the elements of each list.
a = ['a1', 'a2', 'a3'] b = ['b1', 'b2', 'b3'] for x, y in zip(a, b): print(x, y)
You can also use a list comprehension to create a new list with the interleaved elements and then use the print() function to print it:
a = ['a1', 'a2', 'a3'] b = ['b1', 'b2', 'b3'] result = [x + y for x, y in zip(a, b)] print(result)
It is important to remember that the zip() function will only iterate over the elements of the lists until the shortest list is exhausted. If the lists have different lengths, the elements of the longer list will not be included in the output. For example:
a = ['a1', 'a2', 'a3'] b = ['b1', 'b2'] for x, y in zip(a, b): print(x, y)
If you want to include all the elements of the longer list, you can pad the shorter list with None values using the itertools.zip_longest() function from the itertools module. For example:
import itertools a = ['a1', 'a2', 'a3'] b = ['b1', 'b2'] for x, y in itertools.zip_longest(a, b): print(x, y)
9. Print a Nested Python List
To print a nested list in Python, you can use a loop to iterate over the elements of the outer list and then use another loop to iterate over the elements of the inner list(s). For example:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for sublist in nested_list: for item in sublist: print(item)
We can also print each list in separate lines:
We can also print each list in separate lines: >>> nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> for sublist in nested_list: . print(*sublist, sep=",")
Next, we can use a list comprehension to create a new list with the elements of the nested list and then use the print() function to print the list:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] result = [item for sublist in nested_list for item in sublist]
Lists are powerful and can also be combined with sets and other Python data structures.
10+. There’s Always More …
Here are a few more ways to print lists in Python:
for i in range(len(pokemon_list)): print(pokemon_list[i])
- Another option is to use the pprint module, which provides a pprint() function to pretty-print lists and other data structures:
import pprint pokemon_list = ['Pikachu', 'Abra', 'Charmander'] pprint.pprint(pokemon_list)
- It is also possible to use the json module, which provides a dumps() function that can convert a list to a JSON string:
import json pokemon_list = ['Pikachu', 'Abra', 'Charmander'] print(json.dumps(pokemon_list))
- Last but not least, you can also use the f-strings feature (available in Python 3.6 and later).This feature allows you to embed expressions inside string literals using the <> placeholder:
for pokemon in pokemon_list: print(f' is a pokemon')
Pikachu is a pokemon Abra is a pokemon Charmander is a pokemon
Beyond Printing Lists in Python
In this article, we explored many ways of printing a list in Python. But there’s more, such as printing a Python list sorted alphabetically.
As you’ve seen in this article, there are plenty of ways to work with strings in Python. You can take advantage of our course on Working with Strings in Python to expand your knowledge about this important data type.
Feel free to read more content on LearnPython.com to keep learning. And if you haven’t started your journey yet, now is a good time to start programming in Python!
Python Program to display elements of an array
In this simple python program, we need to display elements of a python array. It’s an array python program.
To understand this example, you should have knowledge of the following Python programming topics:
How to display the elements of an array in python?
An array is a set of elements of the same data type accessed using a common variable index. In python language, we use the List instead of Array but with all the array characteristics. In this simple python program, we need to print all the elements of an array.
For example, suppose we have an array named A, and it has some integers like 1, 2, 3, 4, 5. We have to access these elements using A[i] where i is from 0 to 4. a[0] is 1, a[1] = 2 like that. Here, we use a for loop to traverse through the python array from zero to four and print the numbers inside each array location using a[i].
ALGORITHM
STEP 1: We have to initialize an array A. We can use an input method also if the user wants to insert the array elements in the Python programming language.
STEP 2: Using a print statement, print ‘the array elements are ‘.
STEP 3: Use a for loop from 0 to the length of an array using the range() method, where the length of the array is calculated using the len() method in python.
STEP 4: Print each element in the array in each iteration of the for loop using index A[i]
Python Source Code
A = [1, 2, 3, 4, 5]; # initialize the array A print("Array elements are: "); for i in range(0, len(A)): # for loop to traverse through each element in array print(A[i]),
OUTPUT
Array elements are: 1 2 3 4 5