How to get first N items from a list in Python

Hello Python learner, you are here to learn how to get first n items from a list in Python. So, we will show you an easy way to fetch first n number of items from a list in Python with some easy examples. I hope this is going to be helpful to you.

From my previous tutorials, you can also learn,

Sometimes it really becomes important for us to get the first specific number of items from a list in Python. So I am here to provide a code snippet to help you out.

Get first N items from a list in Python

To give you a better understand, I will create a list first with some elements in it.



my_list = ['How','When','What','Where','CodeSpeedy','Python']

Now we will get the first 4 elements from this list

my_list = ['How','When','What','Where','CodeSpeedy','Python']
print(my_list[:4])

Output:

['How', 'When', 'What', 'Where']

Fetch first N items from a list in Python using loop

Now here’s another technique that you can use to get the first n items from a list in Python.

Take a look at this below code snippet:

my_list = ['How','When','What','Where','CodeSpeedy','Python']

for y in range(4):
    print(my_list[y])

It will print the first 4 items from the list. But this will not be printed as a list. This will be printed like this:

How
When
What
Where

Process finished with exit code 0

I hope you have got my point. So use any of those depending on your requirement.

 

Leave a Reply

Your email address will not be published. Required fields are marked *