Problem: How to append elements to a list using a single line for loop?
Example: You hope to accomplish something like this where you create an initial list (this one is empty) and you append multiple elements to it:
# WRONG CODE: >>> [].append(i) for i in range(5) [0, 1, 2, 3, 4]
However, this statement doesn’t work! Is there a one-line for loop to append elements to a given list?
Let’s dive into several methods to accomplish this! Here’s a quick overview:
Exercise: Can you modify the code to append elements in a tuple to the given list in a single line of code?
Let’s dive into the three methods in more detail!
Method 1: Use List Comprehension
If you don’t need to add elements to a given list but you’re fine to create a new list, list comprehension is your best shot!
# Method 1 lst = [i for i in range(5)] print(lst) # [0, 1, 2, 3, 4]
This one-liner accomplishes the desired result—but it does create a new list. Let’s quickly recap how list comprehension works in this video:
List comprehension is a compact way of creating lists. The simple formula is [expression + context]
.
- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of
for
andif
statements.
The example [x for x in range(3)]
creates the list [0, 1, 2]
.
But is there another way if you have a list and you just want to append elements to this list?
Method 2: Single-Line For Loop with append()
Sure! You can write blocks in a single line—if the block body itself is not nested!
# Method 2 friends = ['Ann', 'Alice'] new_friends = ['Bob', 'Liz'] # One-Liner: for f in new_friends: friends.append(f) # Results print(friends) # ['Ann', 'Alice', 'Bob', 'Liz']
You use the list.append()
method repeatedly for each element in the iterable new_friends
that contains the elements to be appended to the original list friends
. The fact that the for loop is compressed in a single line doesn’t make this one-liner ambiguous so Python is okay with it.
Method 3: extend()
However, a much better option to append all elements in a given iterable to a given list is to use the list.extend()
method:
# Method 3 friends = ['Ann', 'Alice'] new_friends = ['Bob', 'Liz'] # One-Liner: friends.extend(new_friends) # Results print(friends) # ['Ann', 'Alice', 'Bob', 'Liz']
The one-liner is much shorter and even faster. You can find a detailed speed comparison here.
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.