In Python, we can easily get and print the first n items of a list. To do so, we can use slicing and then use a loop to print each item. Below is a simple example showing how to print the first 10 items in a list.
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for x in list[:10]:
print(x)
#Output:
0
1
2
3
4
5
6
7
8
9
When working with lists in our code, it can be useful to get the first few items from a collection.
We can easily use Python to get the first n elements in a list.
There are a few ways we can get the first n elements in a list to be able to print the items from a list in Python.
The easiest way to get the first n elements from a list is to use slicing in Python. Below shows the syntax of how to use slicing to get the first n elements of a list.
first_n_items = list[:n]
We can use this to print the first n elements of a list in Python.
Below is an example of how to print the first 5 elements from a list.
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for x in list[:5]:
print(x)
#Output:
0
1
2
3
4
Printing the First 10 Items in List Using Python
Using Python, we can print the first 10 items of a list easily.
To do so, we just need to get the first 10 items, and then print them to the console.
We can print the first 10 items using a loop in Python as shown below.
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for x in list[:10]:
print(x)
#Output:
0
1
2
3
4
5
6
7
8
9
You can also use the Python * operator to print out a list as well.
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(*list[:10])
#Output:
0 1 2 3 4 5 6 7 8 9
How to Print the Last N Elements of a List
We can also print the last n elements of a list easily in Python.
In Python, we can easily get the last n elements of a list using slicing.
Below shows how we can use slicing in Python to get and print the last n elements of a list.
list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0]
last_5_numbers = list_of_numbers[-5:]
print(*last_5_numbers)
#Output:
0 3 0 -1 0
Hopefully this article has been useful for you to understand how to print the first n items of a list in Python.