Python One Line Append

Do you want to one-linerize the append() method in Python? I feel you—writing short and concise one-liners can be an addiction! 🙂

This article will teach you all the ways to append one or more elements to a list in a single line of Python code!

Python List Append

Let’s quickly recap the append method that allows you add an arbitrary element to a given list.

How can you add an elements to a given list? Use the append() method in Python.

Definition and Usage

The list.append(x) method—as the name suggests—appends element x to the end of the list.

Here’s a short example:

>>> l = []
>>> l.append(42)
>>> l
[42]
>>> l.append(21)
>>> l
[42, 21]

In the first line of the example, you create the list l. You then append the integer element 42 to the end of the list. The result is the list with one element [42]. Finally, you append the integer element 21 to the end of that list which results in the list with two elements [42, 21].

Syntax

You can call this method on each list object in Python. Here’s the syntax:

list.append(element)

Arguments

ArgumentDescription
elementThe object you want to append to the list.

Related articles:

Python One Line List Append

Problem: How can you create a list and append an element to a list using only one line of Python code?

You may find this challenging because you must accomplish two things in one line: (1) creating the list and (2) appending an element to it.

Solution: We use the standard technique to one-linerize each “flat” multi-line code snippet: with the semicolon as a separator between the expressions.

a = [1, 2, 3]; a.append(42); print(a)

This way, we accomplish three things in a single line of Python code:

  • Creating the list [1, 2, 3] and assigning it to the variable a.
  • Appending the element 42 to the list referred to by a.
  • Printing the list to the shell.

Related Article: Python One Line to Multiple Lines

Python One Line For Append

Problem: How can we append multiple elements to a list in a for loop but using only a single line of Python code?

Example: Say, you want to filter a list of words against another list and store the resulting words in a new list using the append() method in a for loop.

# FINXTER TUTORIAL:
# How to filter a list of words?

words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = []

for word in words:
    if word not in stop_words:
        filtered_words.append(word)

print(filtered_words)
# ['hi', 'hello', 'Python']

You first create a list of words to be filtered and stored in an initially empty list filtered_words. Second, you create a set of stop words against you want to check the words in the list. Note that it’s far more efficient to use the set data structure for this because checking membership in sets is much faster than checking membership in lists. See this tutorial for a full guide on Python sets.

You now iterate over all elements in the list words and add them to the filtered_words list if they are not in the set stop_words.

Solution: You can one-linerize this filtering process using the following code:

filtered_words = [word for word in words if word not in stop_words]

The solution uses list comprehension to, essentially, create a single-line for loop.

Here’s the complete code that solves the problem using the one-liner filtering method:

# FINXTER TUTORIAL:
# How to filter a list of words?

words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [word for word in words if word not in stop_words]

print(filtered_words)
# ['hi', 'hello', 'Python']

Here’s a short tutorial on filtering in case you need more explanations:

Related Article: How to Filter a List in Python?

Python One Line If Append

In the previous example, you’ve already seen how to use the if statement in the list comprehension statement to append more elements to a list if they full-fill a given condition.

How can you filter a list in Python using an arbitrary condition? The most Pythonic and most performant way is to use list comprehension [x for x in list if condition] to filter all elements from a list.

Try It Yourself:

The most Pythonic way of filtering a list—in my opinion—is the list comprehension statement [x for x in list if condition]. You can replace condition with any function of x you would like to use as a filtering condition.

For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement [x for x in list if x<10] to create a new list with all list elements that are smaller than 10.

Here are three examples of filtering a list:

  • Get elements smaller than eight: [x for x in lst if x<8].
  • Get even elements: [x for x in lst if x%2==0].
  • Get odd elements: [x for x in lst if x%2].
lst = [8, 2, 6, 4, 3, 1]

# Filter all elements <8
small = [x for x in lst if x<8]
print(small)


# Filter all even elements
even = [x for x in lst if x%2==0]
print(even)

# Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)

The output is:

# Elements <8
[2, 6, 4, 3, 1]

# Even Elements
[8, 2, 6, 4]

# Odd Elements
[3, 1]

This is the most efficient way of filtering a list and it’s also the most Pythonic one. If you look for alternatives though, keep reading because I’ll explain to you each and every nuance of filtering lists in Python in this comprehensive guide.

Python Append One Line to File

Problem: Given a string and a filename. How to write the string into the file with filename using only a single line of Python code?

Example: You have filename 'hello.txt' and you want to write string 'hello world!' into the file.

hi = 'hello world!'
file = 'hello.txt'

# Write hi in file

'''
# File: 'hello.txt':
hello world!
'''

How to achieve this? In this tutorial, you’ll learn four ways of doing it in a single line of code!

Here’s a quick overview in our interactive Python shell:

Exercise: Run the code and check the file 'hello.txt'. How many 'hello worlds!' are there in the file? Change the code so that only one 'hello world!' is in the file!

The most straightforward way is to use the with statement in a single line (without line break).

hi = 'hello world!'
file = 'hello.txt'

# Method 1: 'with' statement
with open(file, 'a') as f: f.write(hi)

'''
# File: 'hello.txt':
hello world!
'''

You use the following steps:

  • The with environment makes sure that there are no side-effects such as open files.
  • The open(file, 'a') statement opens the file with filename file and appends the text you write to the contents of the file. You can also use open(file, 'w') to overwrite the existing file content.
  • The new file returned by the open() statement is named f.
  • In the with body, you use the statement f.write(string) to write string into the file f. In our example, the string is 'hello world!'.

Of course, a prettier way to write this in two lines would be to use proper indentation:

with open(file, 'a') as f:
    f.write(hi)

This is the most well-known way to write a string into a file. The big advantage is that you don’t have to close the file—the with environment does it for you! That’s why many coders consider this to be the most Pythonic way.

You can find more ways on my detailed blog article.

Related Article: Python One-Liner: Write String to File

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python 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 tips and tricks, regular expressions, machine learning, core data science topics, and 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.

Get your Python One-Liners Now!!