Posted on Leave a comment

How to Get the Key with Minimum Value in a Python Dictionary?

I have spent my morning hours on an important mission. What is the cleanest, fastest, and most concise answer to the following question: How do you find the key with the minimum value in a Python dictionary?  Most answers on the web say you need to use a library but this is not true!

Simply use the min function with the key argument set to dict.get:

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(min(income, key=income.get))
# Anne

The min function goes over all keys, k, in the dictionary income and takes the one that has minimum value after applying the income.get(k) method. The get() method returns the value specified for key, k, in the dictionary.

Play with it yourself in our interactive code shell:

Now, read the 4-min article or watch the short video to fully understand this concept.

What’s the Min Function in Python?

Most likely, you already know Python’s min(…) function. You can use it to find the minimum value of any iterable or any number of values. Here are a few examples using the min function without specifying any optional arguments.

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(min(income, key=income.get))
# Anne # Key that starts with 'smallest' letter of the alphabet
print(min(income))
# Anne # Smallest value in the dictionary income
print(min(income.values()))
# 1111 # Smallest value in the given list
print(min([1,4,7,5,3,99,3]))
# 1 # Compare lists element-wise, min is first list to have a larger
# element print(min([1,2,3],[5,6,4]))
# [1, 2, 3] # Smallest value in the given sequence of numbers
print(min(5,7,99,88,123))
# 5

So far so good. The min function is very flexible. It works not only for numbers but also for strings, lists, and any other object you can compare against other objects.

Now, let’s look at the optional arguments of the min function. One of them is 'key'. Let’s find out what it does.

How Does the Key Argument of Python’s min() Function Work?

The last examples show the intuitive workings of the min function: you pass one or more iterables as positional arguments.


Intermezzo: What are iterables? An iterable is an object from which you can get an iterator. An iterator is an object on which you can call the next() method. Each time you call next(), you get the ‘next’ element until you’ve got all the elements from the iterator. For example, Python uses iterators in for loops to go over all elements of a list, all characters of a string, or all keys in a dictionary.


When you specify the key argument, define a function that returns a value for each element of the iterable. Then each element is compared based on the return value of this function, not the iterable element (the default behavior).

Here is an example:

lst = [2, 4, 8, 16] def inverse(val): return -val print(min(lst))
# 2 print(min(lst, key=inverse))
# 16

We define a function inverse() that returns the value multiplied by -1. Now, we print two executions of the min() function.

  • The first is the default execution: the minimum of the list [2, 4, 8, 16] is 2.
  • The second uses key. We specify inverse as the key function. Python applies this function to all values of [2, 4, 8, 16]. It compares these new values with each other and returns the min. Using the inverse function Python does the following mappings:
Original Value  Value after inverse() (basis for min())
2 -2
4 -4
8 -8
16 -16

Python calculates the minimum based on these mappings. In this case, the value 16 (with mapping -16) is the minimum value because -2 > -4 > -8 > -16. 

Now let’s come back to the initial question:

How to Get the Key with the Minimum Value in a Dictionary?

We use the same example as above. The dictionary stores the income of three persons John, Mary, and Alice. Suppose you want to find the person with the smallest income. In other words, what is the key with the minimum value in the dictionary?

Now don’t confuse the dictionary key with the optional key argument of the min() function. They have nothing in common – it’s just an unfortunate coincidence that they have the same name!

From the problem, we know the result is a dictionary key. So, we call min() on the keys of the dictionary. Note that min(income.keys()) is the same as min(income).

To learn more about dictionaries, check out our article Python Dictionary – The Ultimate Guide.

However, we want to compare dictionary values, not keys. We’ll use the key argument of min() to do this. We must pass it a function but which? 

To get the value of 'Anne', we can use bracket notation – income['Anne']. But bracket notation is not a function, so that doesn’t work. Fortunately, income.get('Anne') does (almost) the same as income['Anne'] and it is a function! The only difference is that it returns None if they key is not in the dictionary. So we’ll pass that to the key argument of min().

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(min(income, key=income.get))
# Anne

How to Get the Key with the Maximum Value in a Dictionary?

If you understood the previous code snippet, this one will be easy. To find the key with maximum value in the dictionary, you use the max() function.

income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(max(income, key=income.get))
# Cara

The only difference is that you use the built-in max() function instead of the built-in min() function. That’s it.

Related article:

Find the Key with the Min Value in a Dictionary – Alternative Methods

There are lots of different ways to solve this problem. They are not as beautiful or clean as the above method. But, for completeness, let’s explore some more ways of achieving the same thing.

In a StackOverflow answer, a user compared nine (!) different methods to find the key with the minimum value in a dictionary. Here they are:

income = {'Anne' : 11111, 'Bert' : 2222, 'Cara' : 9999999} # Convert to lists and use .index(max())
def f1(): v=list(income.values()) k=list(income.keys()) return k[v.index(min(v))] # Dictionary comprehension to swap keys and values
def f2(): d3={v:k for k,v in income.items()} return d3[min(d3)] # Use filter() and a lambda function
def f3(): return list(filter(lambda t: t[1]==min(income.values()), income.items()))[0][0] # Same as f3() but more explicit
def f4(): m=min(income.values()) return list(filter(lambda t: t[1]==m, income.items()))[0][0] # List comprehension
def f5(): return [k for k,v in income.items() if v==min(income.values())][0] # same as f5 but remove the max from the comprehension
def f6(): m=min(income.values()) return [k for k,v in income.items() if v==m][0] # Method used in this article
def f7(): return min(income,key=income.get) # Similar to f1() but shortened to 2 lines
def f8(): v=list(income.values()) return list(income.keys())[v.index(min(v))] # Similar to f7() but use a lambda function
def f9(): return min(income, key=lambda k: income[k]) print(f1())
print(f2())
print(f3())
print(f4())
print(f5())
print(f6())
print(f7())
print(f8())
print(f9())
# Bert (all outputs)

In a benchmark performed on a large dictionary by the StackOverflow user, f1() turned out to be the fastest one.

So the second best way to get the key with the minimum value from a dictionary is:

income = {'Anne' : 11111, 'Bert' : 2222, 'Cara' : 9999999} v=list(income.values())
k=list(income.keys())
print(k[v.index(min(v))])
# Bert

Find Key with Shortest Value in Dictionary

We know how to find the minimum value if the values are numbers. What about if they are lists or strings?

Let’s say we have a dictionary that records the number of days each person worked this month. If they worked a day, we append 1 to that person’s list. If they didn’t work, we don’t do anything.  At the end of the month, our dictionary looks like this.

days_worked = {'Anne': [1, 1, 1, 1], 'Bert': [1, 1, 1, 1, 1, 1], 'Cara': [1, 1, 1, 1, 1, 1, 1, 1]}

The total number of days worked each month is the length of each list. If all elements of two lists are the same (as is the case here), they are compared based on their length.

# Length 2 is less than length 4
>>> [1, 1] < [1, 1, 1, 1]
True

So we can use the same code we’ve been using in the article to find the key with the minimum value.

>>> min(days_worked, key=days_worked.get) 'Anne'

If we update our dictionary so that Bert has worked the most days and apply min() again, Python returns 'Anne'.

>>> days_worked = {'Anne': [1, 1, 1, 1], 'Bert': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'Cara': [1, 1, 1, 1, 1, 1, 1, 1]} # Anne has now worked the least
>>> min(days_worked, key=days_worked.get)

Find Key With Min Value in a List of Dictionaries

Let’s say we have 3 dictionaries containing income information. We want to find the key with the min value from all 3 dictionaries. 

income1 = {'Anne': 1111, 'Bert': 2222, 'Cara': 3333} income2 = {'Dani': 4444, 'Ella': 5555, 'Fred': 6666} income3 = {'Greg': 7777, 'Hope': 8888, 'Igor': 999999999999} list_of_dicts = [income1, income2, income3]

We can see that 'Anne' has the lowest income so we expect that to be returned.

There are several ways to do this. The simplest is to put all key-value pairs into one dictionary using a for loop. Then we call min() as usual.

# Initialise empty dict
>>> big_dict = {} # Use for loop and .update() method to add the key-value pairs
>>> for dic in list_of_dicts: big_dict.update(dic) # Check the result is as expected
>>> big_dict
{'Anne': 1111, 'Bert': 2222, 'Cara': 3333, 'Dani': 4444, 'Ella': 5555, 'Fred': 6666, 'Greg': 7777, 'Hope': 8888, 'Igor': 999999999999} # Call min() and specify key argument
>>> min(big_dict, key=big_dict.get) 'Anne' 

Where to Go From Here?

Every Python master must know the basics. Improving your basic code understanding skills by 20% will improve your productivity by much more than anything else. Why? Because everything else builds upon the basics.

But most material online is tedious and boring. That’s why I’ve written a new and exciting way of learning Python, while measuring and comparing your skills against other coders. Check out the book “Coffee Break Python”. It’s LeanPub 2019 bestseller in the category Python!

Posted on Leave a comment

Python List Length – What’s the Runtime Complexity of len()?

The runtime complexity of the len() function on your Python list is O(1). It takes constant runtime no matter how many elements are in the list. Why? Because the list object maintains an integer counter that increases and decreases as you add and remove list elements. Looking up the value of this counter takes constant time.

Python list objects keep track of their own length. When you call the function len(...) on a list object, here’s what happens (roughly):

  • The Python virtual machine looks up the len(...) function in a dictionary to find the associated implementation.
  • You pass a list object as an argument to the len() function so the Python virtual machine checks the __len__ method of the list object.
  • The method is implemented in C++ and it’s just a counter that’s increased each time you add an element to the list and decreased if you remove an element from the list. For example, say, the variable length stores the current length of the list. The method then returns the value self.length.
  • Done.

Here’s a snippet of the C++ implementation of the list data structure:

static int
list_resize(PyListObject *self, Py_ssize_t newsize)
{ PyObject **items; size_t new_allocated, num_allocated_bytes; Py_ssize_t allocated = self->allocated; // some implementation details Py_SET_SIZE(self, newsize); self->allocated = new_allocated; return 0;
}

What’s the Runtime Complexity of Other Python List Methods?

Here’s the table based on the official Python wiki:

Operation Average Case Amortized Worst Case
copy() O(n) O(n)
append() O(1) O(1)
pop() O(1) O(1)
pop(i) O(k) O(k)
insert() O(n) O(n)
list[i] O(1) O(1)
list[i] = x O(1) O(1)
remove(x) O(n) O(n)
for i in list O(n) O(n)
list[i:j] O(k) O(k)
del list[i:j] O(n) O(n)
list[i:j] = y O(k+n) O(k+n)
extend() O(k) O(k)
sort() O(n log n) O(n log n)
[…] * 10 O(nk) O(nk)
x in lst O(n)
min(lst), max(lst) O(n)
len(lst) O(1) O(1)

The Python list is implemented using a C++ array. This means that it’s generally slow to modify elements at the beginning of each list because all elements have to be shifted to the right. If you add an element to the end of a list, it’s usually fast. However, resizing an array can become slow from time to time if more memory has to be allocated for the array.

Where to Go From Here

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.

Posted on Leave a comment

How to Create Your Own Search Engine in a Single Line of Python?

This Python One-Liner is part of my Python One-Liners book with NoStarch Press.

Here’s the code from the video:

letters_amazon = '''
We spent several years building our own database engine,
Amazon Aurora, a fully-managed MySQL and PostgreSQL-compatible
service with the same or better durability and availability as
the commercial engines, but at one-tenth of the cost. We were
not surprised when this worked. ''' find = lambda x, q: x[x.find(q)-18:x.find(q)+18] if q in x else -1 print(find(letters_amazon, 'SQL'))

Try It Yourself:

Related Articles:

Posted on Leave a comment

Python – How to Sort a List of Dictionaries?

In this article, you’ll learn the ins and outs of the sorting function in Python. In particular, you’re going to learn how to sort a list of dictionaries in all possible variations. [1] So let’s get started!

How to Sort a List of Dictionaries …

… By Value?

Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. You want to sort them by value of a particular dictionary key (attribute). How do you sort this dictionary?

Minimal Example: Consider the following example where you want to sort a list of salary dictionaries by value of the key 'Alice'.

salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] sorted_salaries = # ... Sorting Magic Here ... print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'Alice': 12000, 'Bob': 66000},
{'Alice': 100000, 'Bob': 24000},
{'Alice': 121000, 'Bob': 48000}]

Solution: You have two main ways to do this—both are based on defining the key function of Python’s sorting methods. The key function maps each list element (in our case a dictionary) to a single value that can be used as the basis of comparison.

  • Use a lambda function as key function to sort the list of dictionaries.
  • Use the itemgetter function as key function to sort the list of dictionaries.

Here’s the code of the first option using a lambda function that returns the value of the key 'Alice' from each dictionary:

# Create the dictionary of Bob's and Alice's salary data
salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] # Use the sorted() function with key argument to create a new dic.
# Each dictionary list element is "reduced" to the value stored for key 'Alice'
sorted_salaries = sorted(salaries, key=lambda d: d['Alice']) # Print everything to the shell
print(sorted_salaries)

The output is the sorted dictionary. Note that the first dictionary has the smallest salary of Alice and the third dictionary has the largest salary of Alice.

[{'Alice': 12000, 'Bob': 66000}, {'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}]

Try It Yourself:

You’ll learn about the second way below (where you use the itemgetter function from the operator module).

Related articles on the Finxter blog:

… Using Itemgetter?

Same Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. How to sort them by value of a particular dictionary key (attribute)?

Minimal Example: Consider again the following example where you want to sort a list of salary dictionaries by value of the key 'Alice'.

salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] sorted_salaries = # ... Sorting Magic Here ... print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'Alice': 12000, 'Bob': 66000},
{'Alice': 100000, 'Bob': 24000},
{'Alice': 121000, 'Bob': 48000}]

Solution: Again, you’re going to define a key function. But instead of creating it yourself with the lambda keyword, you’re going to use an existing one. In particular, you’ll use the itemgetter function from the operator module to sort the list of dictionaries.

Here’s the code of the first option using a lambda function that returns the value of the key 'Alice' from each dictionary:

# Import the itemgetter function from the operator module
from operator import itemgetter # Create the dictionary of Bob's and Alice's salary data
salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] # Use the sorted() function with key argument to create a new dic.
# Each dictionary list element is "reduced" to the value stored for key 'Alice'
sorted_salaries = sorted(salaries, key=itemgetter('Alice')) # Print everything to the shell
print(sorted_salaries)

The output is the sorted dictionary. Note that the first dictionary has the smallest salary of Alice and the third dictionary has the largest salary of Alice.

[{'Alice': 12000, 'Bob': 66000}, {'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}]

Now, you know how to sort a list of dictionaries by value. But what if you want to sort by key?

… By Key?

Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. How to sort them by a particular key (attribute)?

Solution: It doesn’t make sense. If you assume that all dictionaries have that same particular key, you cannot really sort because all dictionaries have the same key. If there’s no tie-breaker, it’s impossible to do. But even if there’s a tie-breaker (e.g. the value associated to the key), it doesn’t make sense because you could have sorted by value in the first place.

… By Multiple Keys?

Problem: Given a list of dictionaries. How do you sort by multiple key value pairs?

Minimal Example: Consider the following example where you want to sort a list of database entries (e.g. each stored as a dictionary) by value of the key 'username'. If the 'username' is the same, you use the 'joined' value as a tiebreaker. If the 'joined' date is the same, you use the 'age' as a tie breaker.

db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] sorted_salaries = # ... Sorting Magic Here ... print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Alice', 'joined': 2020, 'age': 31}, {'username': 'Bob', 'joined': 2018, 'age': 19}]

Solution: You’re going to define a key function with the lambda keyword. But instead of returning a single value to a given key, you return a tuple—one entry per value that should be considered. For example, the database entry {'username': 'Alice', 'joined': 2020, 'age': 23} is mapped to ('Alice', 2020, 23). This ensures that two tuples that have the same first tuple value will still be sorted correctly by using the second tuple value as a tiebreaker.

Here’s the code:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the tuple of values.
db_sorted = sorted(db, key=lambda row: (row['username'], row['joined'], row['age'])) # Print everything to the shell
print(db_sorted)

The output is the sorted dictionary. Note that the first dictionary has the smallest salary of Alice and the third dictionary has the largest salary of Alice.

[{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Alice', 'joined': 2020, 'age': 31}, {'username': 'Bob', 'joined': 2018, 'age': 19}]

In this example, the dictionary value for the key ‘joined’ was an integer number. But what if it’s a date?

… By Date?

Problem: Given a list of dictionaries. How do you sort the list of dictionaries by date?

Minimal Example: Consider the following example where you want to sort a list of database entries (e.g. each stored as a dictionary) by value of the key 'joined' that is from type date or timedate.

db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] db_sorted = # ... sorting magic here ... print(db_sorted)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}]

Solution: Define a key function with the lambda keyword. Simply return the string value for the key 'joined' for a given dictionary. This return value is then used to sort the dictionaries in the list.

As the join dates are given as strings in the form year-month-day (e.g. '2020-08-08'), the default alphabetical sort will also lead to a sorted overall list of dictionaries: the dictionary row with the earliest join date will be the first in the resulting list.

Here’s the code:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined']) # Print everything to the shell
print(db_sorted)

The output is the sorted dictionary. Note that the first dictionary has the earliest and the third dictionary has the latest join date.

[{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}]

You can use a similar method if the dictionary values are of format datetime as they are also comparable with default comparison operators >, <, >=, <=, and ==. [2]

… In Descending Order?

Problem: The default ordering of any Python list sort routine (sorted() and list.sort()) is in ascending order. This also holds if you sort a list of dictionaries. How can you sort in descending order?

Solution: If you want to sort in descending order, you can do one of the following:

  • Use slicing to reverse the sorted list.
  • Use the reverse=True argument of the sorted() or list.sort() methods.

Both ways are equivalent. Have a look at the previous example first using the reverse argument:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined'], reverse=True) # Print everything to the shell
print(db_sorted)

Output:

[{'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Alice', 'joined': '2019-03-02', 'age': 23}]

And second using slicing with negative step size (without the reverse argument):

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined'])[::-1] # Print everything to the shell
print(db_sorted)

Same output:

[{'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Alice', 'joined': '2019-03-02', 'age': 23}]

… in Ascending Order?

The default ordering of any Python list sort routine (sorted() and list.sort()) is in ascending order. This also holds if you sort a list of dictionaries.

Where to Go From Here

In this article, you’ve learned how to sort a list of dictionaries. In summary, use the sorted() method with a key function as argument. This gives you the flexibility to customize how exactly you want to sort the dictionary—just map each dictionary to a comparable value.

I’ve realized that professional coders tend to use dictionaries more often than beginners due to their superior understanding of the benefits of dictionaries. If you want to learn about those, check out my in-depth tutorial of Python dictionaries.

If you want to stop learning and start earning with Python, check out my free webinar “How to Become a Python Freelance Developer?”. It’s a great way of starting your thriving coding business online.

“[Webinar] How to Become a Python Freelance Developer?”

Posted on Leave a comment

Matplotlib 3D Plot – A Helpful Illustrated Guide

Are you tired with the same old 2D plots? Do you want to take your plots to the next level? Well look no further, it’s time to learn how to make 3D plots in matplotlib.

In addition to import matplotlib.pyplot as plt and calling plt.show(), to create a 3D plot in matplotlib, you need to:

  1. Import the Axes3D object
  2. Initialize your Figure and Axes3D objects
  3. Get some 3D data
  4. Plot it using Axes notation and standard function calls
# Standard import
import matplotlib.pyplot as plt # Import 3D Axes from mpl_toolkits.mplot3d import axes3d # Set up Figure and 3D Axes fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Get some 3D data
X = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Y = [2, 5, 8, 2, 10, 1, 10, 5, 7, 8]
Z = [6, 3, 9, 6, 3, 2, 3, 10, 2, 4] # Plot using Axes notation and standard function calls
ax.plot(X, Y, Z)
plt.show()

Awesome! You’ve just created your first 3D plot! Don’t worry if that was a bit fast, let’s dive into a more detailed example.

Try it yourself with our interactive Python shell. Just execute the code and look at the generated “plot.png” file:

Related article:

Matplotlib 3D Plot Example

If you are used to plotting with Figure and Axes notation, making 3D plots in matplotlib is almost identical to creating 2D ones. If you are not comfortable with Figure and Axes plotting notation, check out this article to help you.

Besides the standard import matplotlib.pyplot as plt, you must alsofrom mpl_toolkits.mplot3d import axes3d. This imports a 3D Axes object on which a) you can plot 3D data and b) you will make all your plot calls with respect to.

You set up your Figure in the standard way

fig = plt.figure()

And add a subplots to that figure using the standard fig.add_subplot() method. If you just want a single Axes, pass 111 to indicate it’s 1 row, 1 column and you are selecting the 1st one. Then you need to pass projection='3d' which tells matplotlib it is a 3D plot.

From now on everything is (almost) the same as 2D plotting. All the functions you know and love such as ax.plot() and ax.scatter() accept the same keyword arguments but they now also accept three positional arguments – X,Y and Z.

In some ways 3D plots are more natural for us to work with since we live in a 3D world. On the other hand, they are more complicated since we are so used to 2D plots. One amazing feature of Jupyter Notebooks is the magic command %matplotlib notebook which, if ran at the top of your notebook, draws all your plots in an interactive window. You can change the orientation by clicking and dragging (right click and drag to zoom in) which can really help to understand your data.

As this is a static blog post, all of my plots will be static but I encourage you to play around in your own Jupyter or IPython environment.

Related article:

Matplotlib 3D Plot Line Plot

Here’s an example of the power of 3D line plots utilizing all the info above.

# Standard imports
import matplotlib.pyplot as plt
import numpy as np # Import 3D Axes from mpl_toolkits.mplot3d import axes3d # Set up Figure and 3D Axes fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Create space of numbers for cos and sin to be applied to
theta = np.linspace(-12, 12, 200)
x = np.sin(theta)
y = np.cos(theta) # Create z space the same size as theta z = np.linspace(-2, 2, 200) ax.plot(x, y, z)
plt.show()

To avoid repetition, I won’t explain the points I have already made above about imports and setting up the Figure and Axes objects.

I created the variable theta using np.linspace which returns an array of 200 numbers between -12 and 12 that are equally spaced out i.e. there is a linear distance between them all. I passed this to np.sin() and np.cos() and saved them in variables x and y.

If you just plotted x and y now, you would get a circle. To get some up/down movement, you need to modify the z-axis. So, I used np.linspace again to create a list of 200 numbers equally spaced out between -2 and 2 which can be seen by looking at the z-axis (the vertical one).

Note: if you choose a smaller number of values for np.linspace the plot is not as smooth.

For this plot, I set the third argument of np.linspace to 25 instead of 200. Clearly, this plot is much less smooth than the original and hopefully gives you an understanding of what is happening under the hood with these plots. 3D plots can seem daunting at first so my best advice is to go through the code line by line.

Matplotlib 3D Plot Scatter

Creating a scatter plot is exactly the same as making a line plot but you call ax.scatter instead.

Here’s a cool plot that I adapted from this video. If you sample a normal distribution and create a 3D plot from it, you get a ball of points with the majority focused around the center and less and less the further from the center you go.

import random
random.seed(1) # Create 3 samples from normal distribution with mean and standard deviation of 1
x = [random.normalvariate(1, 1) for _ in range(400)]
y = [random.normalvariate(1, 1) for _ in range(400)]
z = [random.normalvariate(1, 1) for _ in range(400)] # Set up Figure and Axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Plot
ax.scatter(x, y, z)
plt.show()

First, I imported the python random module and set the seed so that you can reproduce my results. Next, I used three list comprehensions to create 3 x 400 samples of a normal distribution using the random.normalvariate() function. Then I set up the Figure and Axes as normal and made my plot by calling ax.scatter().

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z)
plt.show()

In this example, I plotted the same X, Y and Z lists as in the very first example. I want to highlight to you that some of the points are darker and some are more transparent – this indicates depth. The ones that are darker in color are in the foreground and those further back are more see-through.

If you plot this in IPython or an interactive Jupyter Notebook window and you rotate the plot, you will see that the transparency of each point changes as you rotate.

Matplotlib 3D Plot Rotate

The easiest way to rotate 3D plots is to have them appear in an interactive window by using the Jupyter magic command %matplotlib notebook or using IPython (which always displays plots in interactive windows). This lets you manually rotate them by clicking and dragging. If you right-click and move the mouse, you will zoom in and out of the plot. To save a static version of the plot, click the save icon.

It is possible to rotate plots and even create animations via code but that is out of the scope of this article.

Matplotlib 3D Plot Axis Labels

Setting axis labels for 3D plots is identical for 2D plots except now there is a third axis – the z-axis – you can label.

You have 2 options:

  1. Use the ax.set_xlabel(), ax.set_ylabel() and ax.set_zlabel() methods, or
  2. Use the ax.set() method and pass it the keyword arguments xlabel, ylabel and zlabel.

Here is an example using the first method.

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z) # Method 1
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis') plt.show()

Now each axis is labeled as expected.

You may notice that the axis labels are not particularly visible using the default settings. You can solve this by manually increasing the size of the Figure with the figsize argument in your plt.figure() call.

One thing I don’t like about method 1 is that it takes up 3 lines of code and they are boring to type. So, I much prefer method 2.

# Set Figure to be 8 inches wide and 6 inches tall
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z) # Method 2 - set all labels in one line of code!
ax.set(xlabel='X axis', ylabel='Y axis', zlabel='Z axis') plt.show()

Much better! Firstly, because you increased the size of the Figure, all the axis labels are clearly visible. Plus, it only took you one line of code to label them all. In general, if you ever use a ax.set_<something>() method in matplotlib, it can be written as ax.set(<something>=) instead. This saves you space and is nicer to type, especially if you want to make numerous modifications to the graph such as also adding a title.

Matplotlib 3D Plot Legend

You add legends to 3D plots in the exact same way you add legends to any other plots. Use the label keyword argument and then call ax.legend() at the end.

import random random.seed(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Plot and label original data
ax.scatter(X, Y, Z, label='First Plot') # Randomly re-order the data
for data in [X, Y, Z]: random.shuffle(data) # Plot and label re-ordered data
ax.scatter(X, Y, Z, label='Second Plot') ax.legend(loc='upper left')
plt.show()

In this example, I first set the random seed to 1 so that you can reproduce the same results as me. I set up the Figure and Axes as expected, made my first 3D plot using X, Y and Z and labeled it with the label keyword argument and an appropriate string.

To save me from manually creating a brand new dataset, I thought it would be a good idea to make use of the data I already had. So, I applied the random.shuffle() function to each of X, Y and Z which mixes the values of the lists in place. So, calling ax.plot() the second time, plotted the same numbers but in a different order, thus producing a different looking plot. Finally, I labeled the second plot and called ax.legend(loc='upper left') to display a legend in the upper left corner of the plot.

All the usual things you can do with legends are still possible for 3D plots. If you want to learn more than these basic steps, check out my comprehensive guide to legends in matplotlib.

Note: If you run the above code again, you will get a different looking plot. This is because you will start with the shuffled X, Y and Z lists rather than the originals you created further up inb the post.

Matplotlib 3D Plot Background Color

There are two backgrounds you can modify in matplotlib – the Figure and the Axes background. Both can be set using either the .set_facecolor('color') or the .set(facecolor='color') methods. Hopefully, you know by now that I much prefer the second method over the first!

Here’s an example where I set the Figure background color to green and the Axes background color to red.

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot(X, Y, Z) # Axes color is red
ax.set(facecolor='r')
# Figure color is green
fig.set(facecolor='g')
plt.show()

The first three lines are the same as a simple line plot. Then I called ax.set(facecolor='r') to set the Axes color to red and fig.set(facecolor='g') to set the Figure color to green.

In an example with one Axes, it looks a bit odd to set the Figure and Axes colors separately. If you have more than one Axes object, it looks much better.

# Set up Figure and Axes in one function call
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 6), subplot_kw=dict(projection='3d')) colors = ['r', 'g', 'y', 'b'] # iterate over colors and all Axes objects
for c, ax in zip(colors, axes.flat): ax.plot(X, Y, Z) # Set Axes color ax.set(facecolor=c) # Set Figure color
fig.set(facecolor='pink')
plt.show()

In this example, I used plt.subplots() to set up an 8×6 inch Figure containing four 3D Axes objects in a 2×2 grid. The subplot_kw argument accepts a dictionary of values and these are passed to add_subplot to make each Axes object. For more info on using plt.subplots() check out my article.

Then I created the list colors containing 4 matplotlib color strings. After that, I used a for loop to iterate over colors and axes.flat. In order to iterate over colors and axes together, they need to be the same shape. There are several ways to do this but using the .flat attribute works well in this case.

Finally, I made the same plot on each Axes and set the facecolors. It is clear now why setting a Figure color can be more useful if you create subplots – there is more space for the color to shine through.

Conclusion

That’s it, you now know the basics of creating 3D plots in matplotlib!

You’ve learned the necessary imports you need and also how to set up your Figure and Axes objects to be 3D. You’ve looked at examples of line and scatter plots. Plus, you can modify these by rotating them, adding axis labels, adding legends and changing the background color.

There is still more to be learned about 3D plots such as surface plots, wireframe plots, animating them and changing the aspect ratio but I’ll leave those for another article.

Where To Go From Here?

Do you wish you could be a programmer full-time but don’t know how to start?

Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back!

https://tinyurl.com/become-a-python-freelancer

It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.

These are proven, no-BS methods that get you results fast.

This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.

https://tinyurl.com/become-a-python-freelancer

Posted on Leave a comment

How to Read All Lines of a File in a Python One-Liner?

Say your file is stored in file ‘code.py’. Now, you can open the file, read all lines, get rid of leading and trailing whitespace characters, and store the result in a Python list in a single line of code. Here’s the code:

print([line.strip() for line in open("code.py")])

Python is beautiful! 😍

Try it Yourself:

Where to Go From Here?

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.

Posted on Leave a comment

How to Sort a List Alphabetically in Python?

Problem: Given a list of strings. Sort the list of strings in alphabetical order.

Example:

['Frank', 'Alice', 'Bob'] --> ['Alice', 'Bob', 'Frank']

Solution: Use the list.sort() method without argument to solve the list in lexicographical order which is a generalization of alphabetical order (also applies to the second, third, … characters).

lst = ['Frank', 'Alice', 'Bob']
lst.sort()
print(lst)
# ['Alice', 'Bob', 'Frank']

Try It Yourself:

Python List Sort Alphabetically Case Insensitive

The problem with the default list.sort() or sorted(list) method is that they consider capitalization. This way, it can lead to strange sortings like this:

lst = ['ab', 'Ac', 'ad']
lst.sort()
print(lst)
# ['Ac', 'ab', 'ad']

Intuitively, you would expect the string 'ab' to occur before 'Ac', right?

To ignore the capitalization, you can simply call the x.lower() method on each element x before sorting the list.

However, my preferred method is to use the key argument to accomplish the same thing in a single line of code:

lst = ['ab', 'Ac', 'ad']
lst.sort(key=lambda x: x.lower())
print(lst)
# ['ab', 'Ac', 'ad']

If you like one-liners, you’ll love my new book “Python One-Liners” with NoStarch Press (Amazon Link).

Python List Sort Alphabetically Reverse

You can reverse the order of the list by using the reverse keyword. Set reverse=False to sort in ascending order and set reverse=True to sort in descending order.

lst = ['Frank', 'Alice', 'Bob'] lst.sort(reverse=False)
print(lst)
# ['Alice', 'Bob', 'Frank'] lst.sort(reverse=True)
print(lst)
# ['Frank', 'Bob', 'Alice']

Python List Sort Alphabetically and Numerically

Problem: You’ve got a list of strings. Each strings contains a number. You want the numbers to sort numerically (e.g. 100 comes after 20, not before) but the characters to sort alphabetically (e.g., 'c' comes before 'd').

Example:

['alice 100', 'alice 20', 'bob 99'] --> ['alice 20', 'alice 100', 'bob 99'

Naive Solution (doesn’t work): Use the list.sort() method to sort the list alphabetically:

lst = ['alice 100', 'alice 20', 'bob 99']
lst.sort()
print(lst)
# ['alice 100', 'alice 20', 'bob 99']

Because the number 100 comes before 20 in an alphabetical order, the string 'alice 100' is placed before 'alice 20'.

Solution: I found this code on StackOverflow that nicely demonstrates how to do this:

import re def sorted_nicely(l): """ Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] l.sort(key = alphanum_key) lst = ['alice 100', 'alice 20', 'bob 99']
sorted_nicely(lst)
print(lst)
# ['alice 20', 'alice 100', 'bob 99']

The idea is to differentiate characters and numbers and use them as the basis of comparison for the sort routine.

Where to Go From Here?

The list.sort() method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional key argument by passing a function that returns a comparable value for each element in the list. With the optional Boolean reverse argument, you can switch from ascending (reverse=False) to descending order (reverse=True).

If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).

In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!

Get the book from Amazon!

OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.

Posted on Leave a comment

Using data from spreadsheets in Fedora with Python

Python is one of the most popular and powerful programming languages available. Because it’s free and open source, it’s available to everyone — and most Fedora systems come with the language already installed. Python is useful for a wide variety of tasks, but among them is processing comma-separated value (CSV) data. CSV files often start off life as tables or spreadsheets. This article shows how to get started working with CSV data in Python 3.

CSV data is precisely what it sounds like. A CSV file includes one row of data at a time, with data values separated by commas. Each row is defined by the same fields. Short CSV files are often easily read and understood. But longer data files, or those with more fields, may be harder to parse with the naked eye, so computers work better in those cases.

Here’s a simple example where the fields are Name, Email, and Country. In this example, the CSV data includes a field definition as the first row, although that is not always the case.

Name,Email,Country
John Q. Smith,jqsmith@example.com,USA
Petr Novak,pnovak@example.com,CZ
Bernard Jones,bjones@example.com,UK

Reading CSV from spreadsheets

Python helpfully includes a csv module that has functions for reading and writing CSV data. Most spreadsheet applications, both native like Excel or Numbers, and web-based such as Google Sheets, can export CSV data. In fact, many other services that can publish tabular reports will also export as CSV (PayPal for instance).

The Python csv module has a built in reader method called DictReader that can deal with each data row as an ordered dictionary (OrderedDict). It expects a file object to access the CSV data. So if our file above is called example.csv in the current directory, this code snippet is one way to get at this data:

f = open('example.csv', 'r')
from csv import DictReader
d = DictReader(f)
data = []
for row in d: data.append(row)

Now the data object in memory is a list of OrderedDict objects :

[OrderedDict([('Name', 'John Q. Smith'), ('Email', 'jqsmith@example.com'), ('Country', 'USA')]), OrderedDict([('Name', 'Petr Novak'), ('Email', 'pnovak@example.com'), ('Country', 'CZ')]), OrderedDict([('Name', 'Bernard Jones'), ('Email', 'bjones@example.com'), ('Country', 'UK')])]

Referencing each of these objects is easy:

>>> print(data[0]['Country'])
USA
>>> print(data[2]['Email'])
bjones@example.com

By the way, if you have to deal with a CSV file with no header row of field names, the DictReader class lets you define them. In the example above, add the fieldnames argument and pass a sequence of the names:

d = DictReader(f, fieldnames=['Name', 'Email', 'Country'])

A real world example

I recently wanted to pick a random winner from a long list of individuals. The CSV data I pulled from spreadsheets was a simple list of names and email addresses.

Fortunately, Python also has a helpful random module good for generating random values. The randrange function in the Random class from that module was just what I needed. You can give it a regular range of numbers — like integers — and a step value between them. The function then generates a random result, meaning I could get a random integer (or row number!) back within the total number of rows in my data.

So this small program worked well:

from csv import DictReader
from random import Random d = DictReader(open('mydata.csv'))
data = []
for row in d: data.append(row) r = Random()
winner = data[r.randrange(0, len(data), 1)]
print('The winner is:', winner['Name'])
print('Email address:', winner['Email'])

Obviously this example is extremely simple. Spreadsheets themselves include sophisticated ways to analyze data. However, if you want to do something outside the realm of your spreadsheet app, Python may be just the trick!


Photo by Isaac Smith on Unsplash.

Posted on Leave a comment

Python: How to Count Elements in a List Matching a Condition?

I stumbled across this question when browsing through StackOverflow and it got me thinking: what’s the best way to count the number of elements in a list that match a certain condition? Can you generalize this way to both general conditions (e.g. x>3) and regular expressions (e.g. 'a.*')?

Short answer: you can count the number of elements x that match a certain condition(x) by using the one-liner expression sum(condition(x) for x in lst). This creates a generator expression that returns True for each element that satisfies the condition and False otherwise. Since the True and False values are represented by integer 1 and 0 values, you get the number of matching elements by summing over the iterable.

Try it yourself with the interactive code shell:

In case, the browser interpreter doesn’t show up in your browser, here’s the raw Python code:

## FRAMEWORK FOR CONDITIONAL COUNT ## # Define any condition here
def condition(x): return x > 10 # Create the list
lst = [10, 11, 42, 1, 2, 3] # Count the number of matching elements
print(sum(condition(x) for x in lst))
# What's the output?

Related articles:

Python List Count With Condition

How can you count elements under a certain condition in Python? For example, what if you want to count all even values in a list? Or all prime numbers? Or all strings that start with a certain character? There are multiple ways to accomplish this, let’s discuss them one by one.

Say, you have a condition for each element x. Let’s make it a function with the name condition(x). You can define any condition you want—just put it in your function. For example this condition returns True for all elements that are greater than the integer 10:

def condition(x): return x > 10 print(condition(10))
# False print(condition(2))
# False print(condition(11))
# True

But you can also define more complicated conditions such as checking if they are prime numbers.

Python List Count If

How can you count the elements of the list IF the condition is met?

The answer is to use a simple generator expression sum(condition(x) for x in lst):

>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2

The result indicates that there are two elements that are larger than 10. You used a generator expression that returns an iterator of Booleans. Note that the Boolean True is represented by the integer value 1 and the Boolean False is represented by the integer value 0. That’s why you can simply calculate the sum over all Booleans to obtain the number of elements for which the condition holds.

Python List Count Greater / Smaller Than

If you want to determine the number of elements that are greater than or smaller than a specified value, just modify the condition in this example:

>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2

For example, to find the number of elements smaller than 5, use the condition x<5 in the generator expression:

>>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(x<5 for x in lst)
3

Python List Count Zero / Non-Zero

To count the number of zeros in a given list, use the list.count(0) method call.

To count the number of non-zeros in a given list, you should use conditional counting as discussed before:

def condition(x): return x!=0 lst = [10, 11, 42, 1, 2, 0, 0, 0]
print(sum(condition(x) for x in lst))
# 5

Python List Count Lambda + Map

An alternative is to use a combination of the map and the lambda function.

Related articles:

Here’s the code:

>>> sum(map(lambda x: x%2==0, [1, 2, 3, 4, 5]))
2

You count the number of even integers in the list.

  • The lambda function returns a truth value for a given element x.
  • The map function transforms each list element into a Boolean value (1 or 0).
  • The sum function sums up the “1”s.

The result is the number of elements for which the condition evaluates to True.

Python List Count Regex / Count Matches

Given a list of strings. How can you check how many list elements match a certain regex pattern? (If you need a refresher on Python regular expressions, check out my ultimate guide on this blog – it’s really ultimate!)

  • List lst of string elements
  • Pattern p to be matched against the strings in the list.

Solution: Use the concept of generator expressions with the ternary operator.

Related articles:

Here’s the code:

>>> import re
>>> p = 'a...e'
>>> lst = ['annie', 'alice', 'apex']
>>> sum(1 if re.match(p, x) else 0 for x in lst)
2

Python List Count Wildcard

Do you want to count all string occurrences of a given prefix (e.g. prefix "Sus" for strings "Susie", "Susy", "Susi")?

Solution: Again you can use the concept of generator expressions with the ternary operator.

Related articles:

Here’s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the list.

>>> import re
>>> lst = ['Susi', 'Ann', 'Susanne', 'Susy']
>>> pattern = 'Sus.*'
>>> frequency = sum(1 if re.match(pattern, x) else 0 for x in lst)
>>> print(frequency)
3

The generator expression produces a bunch of 1s and 0s—the former if the list element starts with prefix 'Sus' and the latter if it doesn’t. By summing over all elements, you get the number of matches of the wildcard operator.

Where to Go From Here?

You’ve learned how you can get the number of elements that match a certain condition. It can be a Boolean condition or even a regular expression—the framework stays the same.

Do you want to accelerate your learning efficiency? Do you want to work from the comfort of your own home? Do you want to make a comfortable living by coding 3-5 hours for clients online?

Then join my Python freelancer program and take your first steps towards six figures and attainment of your practical code projects in no time!

Are you still unsure? Watch the free software dev online webinar first. It’s fun and you don’t have to have any preknowledge! 😊

Posted on Leave a comment

Python One-Liners – The Ultimate Collection

This resource is meant to be the ultimate collection of Python One-Liners. If you have an idea for a one-liner to be published here, send me a message at chris (at) finxter.com.

Find All Indices of an Element in a List

Say, you want to do the same as the list.index(element) method but return all indices of the element in the list rather than only a single one.

In this one-liner, you’re looking for element 'Alice' in the list [1, 2, 3] so it even works if the element is not in the list (unlike the list.index() method).

lst = [1, 2, 3]
indices = [i for i in range(len(lst)) if lst[i]=='Alice']
index = indices[0] if indices else None
print(index)