How to get first N items from a list in Python
Hello Python learner, I know, you are here to learn how to get the first N items from a list in Python. So, I will show you an easy way to fetch the first n number of items from a Python list with some easy examples. I hope this is going to be a helpful tutorial for 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.
Python program for Getting the first N list elements
To give you a better understanding, I will create a list first with some elements in it:
cities = ['London','Chicago','Amsterdam','Paris','Singapore','Seoul']
As you can see, we have a list that contains some name of cities in it as items.
Now we will get the first 4 elements from this list
cities = ['London','Chicago','Amsterdam','Paris','Singapore','Seoul'] print(cities[:4])
Output:
['London', 'Chicago', 'Amsterdam', 'Paris']
Fetch first N items from a list in Python using for loop
Let’s see another alternative technique that you can use to get the first n items from a list. This time, I am going to use the for loop for this task.
Take a look at the program below where we are using for loop:
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 one:
How When What Where
As you can see in the above output, the first 4 list items are printed and each one of them is a string.
I hope you have got my point. So use any of those depending on your requirement.
Leave a Reply