Cover Image for Head and Tail Function in Python
558 views

Head and Tail Function in Python

The Python can extract first and last elements, or a specified number of elements, from a list using slicing and indexing. There are no built-in functions called “head” and “tail” in Python, but you can achieve the same functionality using list operations.

Here’s how you can get the “head” and “tail” of a list:


Head (First N Elements):
To get the first N elements of a list, you can use slicing. Slicing allows you to create a new list that contains a portion of the original list.

Python
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 3  # Number of elements to get from the beginning

head = my_list[:n]  # Slice from the beginning to index n (exclusive)
print("Head:", head)  # Output: [1, 2, 3]


Tail (Last N Elements):
To get the last N elements of a list, you can use negative indexing along with slicing. Negative indexing allows you to count elements from the end of the list.

Python
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 3  # Number of elements to get from the end

tail = my_list[-n:]  # Slice from the index -n to the end
print("Tail:", tail)  # Output: [8, 9, 10]

In both examples, we use slicing to extract the desired portion of the list. You can adjust the value of n to get a different number of elements from the beginning or end of the list.

Remember that slicing creates a new list with the selected elements; it does not modify the original list.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS