HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

First, last, initial, head, tail of a Python list

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
lastheadfirsttailpythonlistinitial

Problem

To get the first element of a list (also known as the head of the list), you can use lst[0]. This will return the first element of the list, or None if the list is empty.
To get the last element of a list, you can use lst[-1]. This will return the last element of the list, or None if the list is empty.
To get all elements of a list except the last one, you can use lst[:-1]. This will return all elements of the list except the last one, or an empty list if the list is empty.
To get all elements of a list except the first one (also known as the tail of the list), you can use lst[1:]. This will return all elements of the list except the first one, or an empty list if the list is empty.

Solution

def first(lst):
  return lst[0] if lst else None

first([1, 2, 3]) # 1
first([]) # None


To get all elements of a list except the last one, you can use lst[:-1]. This will return all elements of the list except the last one, or an empty list if the list is empty.
To get all elements of a list except the first one (also known as the tail of the list), you can use lst[1:]. This will return all elements of the list except the first one, or an empty list if the list is empty.

Code Snippets

def first(lst):
  return lst[0] if lst else None

first([1, 2, 3]) # 1
first([]) # None
def last(lst):
  return lst[-1] if lst else None

last([1, 2, 3]) # 3
last([]) # None
def initial(lst):
  return lst[:-1]

initial([1, 2, 3]) # [1, 2]
initial([]) # []

Context

From 30-seconds-of-code: first-last-initial-head-tail

Revisions (0)

No revisions yet.