β Problem Formulation: How to assign the first list element to the variable head
and the remaining elements to the variable tail
?
Let’s have a look at the two most Pythonic solutions to this one-liner programming challenge! π
Method 1: Unpacking and Multiple Assignment
Given a list.
The most Pythonic way to unpack the first element into one variable head
and the remaining elements into variable tail
, assigns the list to the tuple of the head
variable and the asterisked *tail
variable like so:
head, *tail = my_list
Here’s a minimal example:
my_list = ['Alice', 'Bob', 'Carl', 'Denise'] head, *tail = my_list print(head) # Alice print(tail) # ['Bob', 'Carl', 'Denise']
The feature used is called iterable unpacking and it is used to assign an iterable to multiple variables. How?
π‘ By specifying the variables on the left of an assignment operator =
and the iterable on the right.
Python attempts to find a suitable mapping from the iterable on the right to the variables on the left.
If one of the variables on the left of the assignment =
operator is asterisked like *tail
, this variable captures “all remaining iterable values” that cannot be captured by the other variables.
Thus, the unpacked form tail now contains an iterable (list) of all remaining values not captured by any other variable on the left.
Method 2: Indexing and Slicing
Given a list.
To unpack the first element into one variable head
and the remaining elements into variable tail
, use indexing and slicing like so:
head, tail = my_list[0], my_list[1:]
Here’s a minimal example:
my_list = ['Alice', 'Bob', 'Carl', 'Denise'] head, tail = my_list[0], my_list[1:] print(head) # Alice print(tail) # ['Bob', 'Carl', 'Denise']
- The variable
head
contains only the first element of the list—accessed via the zero-based indexing schemelst[0]
. - The variable tail contains all remaining elements from the second to the last list element—accessed via the slicing operation my_list[1:] with default stop index (i.e., slices all the way to the right).
You can learn more about slicing in this tutorial—feel free to watch the video too!
Do you love Python One-Liners? I sure do. So much so that I decided to write a book about it: β€οΈ
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.