Contents
Get Python List with First N Elements
There are many ways to get given Python List with first N elements.
You can use slicing to slice the given list and get a new list with the first N elements of the original or source list.
Or, you can access the list using index, and use a looping statement like for loop to get the first N elements.
Another way would be to use list comprehension. This is an overkill to get the first N elements, but would be educative to learn Python programming.
So, based on the requirement, you may choose one of the above approaches to get or create a new list with the first N elements from the source list.
List with First N Elements using Slicing
The syntax to get the list with first N elements using slicing is
new_list = source_list[:N]
The source list is not modified. A new list is created with the first N elements of source list.
Following is an example program, where we initialize a list, and copy the first N elements of the list to a new list using slicing.
Python Program
source_list = [8, 4, 7, 3, 6, 1, 9]
N = 4
new_list = source_list[:N]
print(source_list)
print(new_list)
Run Output
[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3]
The new list contains first 4 elements of source list.
List with First N Elements using For Loop
To get the first N elements of a list, use for loop with range(0, N), create a new empty list, and append the elements of source list to new list in the for loop.
range(0, N) iterates from 0 to N-1, insteps of 1. N is not included.
list.append(element) appends given element to the list.
Following is an example program, where we initialize a list, and use for loop to get the first N elements of the given list.
Python Program
source_list = [8, 4, 7, 3, 6, 1, 9]
N = 4
new_list = []
for index in range(0, N):
new_list.append(source_list[index])
print(source_list)
print(new_list)
Run Output
[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3]
List with First N Elements using List Comprehension
In the following program, we use list comprehension with if condition and collect those items of source list whose index is less than N.
Python Program
source_list = [8, 4, 7, 3, 6, 1, 9]
N = 4
new_list = [x for index, x in enumerate(source_list) if index < N]
print(source_list)
print(new_list)
Run Output
[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3]
Summary
In this tutorial of Python Examples, we learned how to get the list without its last element, with the help of slicing and pop() method.
Related Tutorials
- Python – Count the items with a specific value in the List
- Python Program to Find Duplicate Items of a List
- Python – Get Index or Position of Item in List
- Shuffle Python List
- Python Program to Find Largest Number in a List
- Python – Traverse List except Last Element
- How to Insert Item at Specific Index in Python List?
- Python – Check if List Contains all Elements of Another List
- Python List without Last Element
- How to Sort Python List?