sorted("elvis") == sorted("lives") # True

Table of Contents

## Why Learning about Python Anagrams?

A popular question in programming interviews is to create an anagram checker.

The interviewer wants to test your knowledge about the basic terminology in computer science, and how good you are at developing your own simple algorithms to solve the problems you are facing. In this article, you’ll learn about a simple algorithm to find anagrams in Python.

Most students who have pursued an academic education in computer science, know exactly what to do here. When posed in a coding interview, this question serves as a test that immediately reveals whether you are part of this community. So let’s prepare!

## Problem Formulation

What are anagrams? Two words are anagrams if they consist of the same characters.

? *“An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.” ***(Wikipedia)**

Here are a few examples:

- “listen” → “silent”
- “funeral” → “real fun”
- “elvis” → “lives”

**Challenge**: Create a Python program that checks for two words `x1`

and `x2`

whether `x1`

is an anagram of `x2`

. More precisely: Given are two strings `x1`

and `x2`

. Write a function `is_anagram`

which returns `True`

if string `x2`

an anagram of string `x1`

!

Ok, now you know exactly what to do, right? So, let’s start coding.

## Anagram Checker

The following one-liner solution (from my book Python One-Liners) solves this problem easily and in a very concise way too.

## Python Anagram One-Liner is_anagram = lambda x1, x2: sorted(x1) == sorted(x2)

If you don’t like one-liners, you can also create the same anagram checker function `is_anagram()`

in two lines:

def is_anagram(x1, x2): return sorted(x1) == sorted(x2)

👉 The function `is_anagram(x1, x2)`

simply returns the result of the expression `sorted(x1) == sorted(x2)`

which is `True`

if the sorted character sequences consist of the same characters.

The one-liner solves the problem efficiently and correctly. **Two strings are anagrams if they have the same sorted character sequence**. It’s that easy. There is no need for external dependencies – we simply create a function `is_anagram`

in a single line of code by using the lambda function definition with two arguments `x1`

and `x2`

.

Here’s the output of the two sorted character sequences:

print(sorted("elvis")) # ['e', 'i', 'l', 's', 'v'] print(sorted("lives")) # ['e', 'i', 'l', 's', 'v']

Both strings `"`

and `"lives"`

consist of the same characters, so the sorted list representation is the same. Thus, the result of the three `print()`

statements in the one-liner code snippet is the following:

## Results print(is_anagram("elvis", "lives")) # True print(is_anagram("elvise", "livees")) # True print(is_anagram("elvis", "dead")) # False

## Background sorted()

To learn more about the `sorted()`

function, check out my in-depth tutorial on the Finxter blog or watch the following video:

## Where to Go From Here?

This article gave you the simplest way of finding anagrams in Python. There is no easier way — guaranteed.

If you feel like you need to become better in Python but you don’t know how and have little time, check out my daily “Coffee Break Python” email series with free Python cheat sheets. It’s fun!

## 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

**. You’ll learn about advanced Python features such as**

*boost your coding and analytical skills**,*

**list comprehension****,**

*slicing***,**

*lambda functions***,**

*regular expressions***and**

*map***functions, and**

*reduce***.**

*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 on Amazon!!*

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

print(is_anagram(“live s”, “e l v i s”))

when I included spaces in the strings it said that the two strings

aren’t actually anagrams. How do we account for cases like this?

Good question! 🙂

I would argue that those two strings aren’t actually anagrams, though. They do not consist of exactly the same characters…

You can use – .lower().replace(” “,””).