Posted on Leave a comment

What Does “if __name__ == ‘__main__’” Do in Python?

Today, let’s discuss something that’s all over the place in many code bases: what does if __name__ == '__main__' do in Python?

If you are learning Python programming step by step, you would have bumped into the above piece of code snippet somewhere. Even if you have not, I am sure you will soon come across it, and this might feel like a jerk in your so far smooth journey of learning Python programming. I have been there. I was going through a book on Python programming when I first saw this piece of code, and I thought—wait a minute, did I miss anything on my way up to here? Then I went back, revising the last few pages to figure out what I missed, and this loop went on for a while before I finally sat down to face the demon, and honestly, I smiled when I figured it out, it is that simple. Maybe, we learn this way. We go back and forth, keep jumping, and then one day, the magic happens. The only thing that works is not giving up. 

Today I will try to make this understanding simple for you in a way that will hopefully bring a smile to your face if you have been in the loop of getting a hint of what it is and then keep forgetting.

To understand what is if __name__ == __main__ used for we will dive into some code examples first to understand what __name__ and __main__ are. Then we will cement the learning through another example. So be patient and go through the article carefully. The code snippets may look a little confusing but wait until we explain and see what is happening exactly.

What are __name__ and __main__?

Let us start with __name__. Simply put, __name__ is a special variable that is built-in in Python. 

In Python, we can run code as a source file or, in other words, a python code that runs on its own (read – not imported from some separate Python source file). This sentence may be confusing at the moment, but let us explore this further.

Look at the code snippet below. It is a simple python file with just one line:

print(f" First Module's Name : {__name__}")

Simply put, we are asking Python to print the value that __name__ variable has at this moment. Notice there is no import statement or even any other line of code above it. 

                                                   Figure 1

Check the output in Figure 2 below. We run the above lines of code and find the output 

First Module’s Name : __main__

                                                    Figure 2

We import module1.py into module2.py and ask Python to return the second module’s name (second because this is the second python code we are running) stored in __name__ variable again.

                                                    Figure 3

Interestingly, in Figure 5 below, we have the output 

First Module’s Name : module1

Second Module’s Name : __main__

                                                    Figure 4

The above information summarised simply can be explained as follows. Python starts executing the first line of code found in a Python file, but before it runs anything to show the output, Python defines some special variables. __name__ is one such variable. When the source file is executed on its own i.e, not being imported from some other source code, the __name__ variable is set to value __main__, and hence the output we got in Figure 3 was First Module’s Name : __main__. If you import the file from some other module (as in the code snippet from Figure 4), the value of __name__ variable is set to the name of the module it is imported from. Hence the output in Figure 5.

Now let us look at the sequence of execution.

  1. module1.py in Figure 1 is executed,
  2. Variable __name__ is set to the value __main__
  3. __main__ module is executed, and the output is First Module’s Name : __main__ 
  4. Module2.py in Figure 4 is executed,
  5. Variable __name__ is set to the value module1
  6. module1 is the block of code in module1.py which is executed, and the output is First Module’s Name : module1 
  7. Next, we move on to line 3 in module2.py, the name value is reset to __main__, because this is a fresh piece of code in module2.py, and the output is Second Module’s Name : __main__

Using if __name__ == ‘__main__’

But let’s think only concerning the code in module2.py. In the real world, with module2.py I would not like to print the output from module1.py rather only import some functionality and get output for the lines of code written in module2.py i.e. Second Module’s Name : __main__

But how can we do it? There has to be a way because this seems more logical that way. Refer to the code snippet below in Figure 6.

                                                     Figure 5

So, we will define a function main(), and put the print statement from module1.py inside the main function. Now we use this small trick of using the statement if __name__ == ‘__main__’ and put the main function inside this if statement. Now let’s look at the execution sequence of our program.

  1. We have a main() function where we ask to print the name of the first module stored in the __name__ variable. From the above example, we know the value stored in the __name__ variable is __main__
  2. In line 7, we say if the value in __name__ variable is equal to __main__, only then go ahead and execute the main() function.
  3. Now running the modified module1.py, we can see the output as First Module’s Name : __main__ as expected. Refer to the first output in Figure 7 
  4. Now when we run module2.py, we get the output as Second Module’s Name : __main__

Notice how the output for module2.py has changed now. Although we have imported module1 in our module2.py program, the program in module1.py doesn’t run. Why? Because the value stored in the __name__ variable at this moment is module1 and not __main__. So, using a main() function and if __name__ == ‘__main__’ has put restrictions on execution of lines of code in module1.py as it would only execute module1.py only if __name__ == ‘__main__’

                                                     Figure 6

Putting it all into a real-world example

We now take a more generic example, which would make more sense of all we have discussed above.

  • Have a look at the below code snippet from cubes.py in Figure 8. In line 1 and line 2, we have a function cube(), which takes num as an argument. The function cubes(num) returns the cube of a given number.
  • On line 4, we use a for loop which iterates over a list of numbers from 0 to 9.
  • On line 5, we use the cubes(num) function with i as input to display the cube, as shown in figure 9. Simple enough.

                                                     Figure 7

                                                     Figure 8

In the code snippet from modules.py below in Figure 10, we import cube(num) function from cubes.py and try to print cube of 10 in line 3. Logically, we are trying to use the function cube(num), which returns a cube of any given input number.

                                       Figure 9

However, look at the output below. We have the output of both the programs cubes.py and modules.py. This is not what we intended or wanted to do. 

                                                     Figure 10

Remember the explanation from above where we used if __name__ == ‘__main__’ to limit the execution of code from modules1.py. Let us try and implement the same idea and see if that works here.

In the code snippet from cubesModified.py in Figure 11, we put the for loop and the print statement from cubes.py in the main() function. And again, we use the statement if __name__ == ‘__main__’ to execute code from cubesModified.py only when the value of __name__ variable equals to __main__.

                                                     Figure 11

We run cubesModified.py and get the output as below and per our expectation.

                                                      Figure 12

However, now when we run modulesModified.py where we import cube(num) function from cubesModified.py, it only executes the code from our modulesModified.py as shown in Figure 15, and the output is 1000 because the value stored in the __name__ variable in cubesModified and not __main__.

                                                      Figure 13

                                                      Figure 14

I hope this explanation helps you with a better understanding of what does if __name__ == ‘__main__’. Go ahead and play around with the code in the code editor and cement your understanding. Best of Luck!!

Author

This article is contributed by Finxter Abhigyan Ojha. You can find his Upwork profile here.

Posted on Leave a comment

Dict to List — How to Convert a Dictionary to a List in Python

Summary: To convert a dictionary to a list of tuples, use the dict.items() method to obtain an iterable of (key, value) pairs and convert it to a list using the list(...) constructor: list(dict.items()). To modify each key value pair before storing it in the list, you can use the list comprehension statement [(k', v') for k, v in dict.items()] replacing k' and v' with your specific modifications.

In my code projects, I often find that choosing the right data structure is an important prerequisite to writing clean and effective code. In this article, you’ll learn the most Pythonic way to convert a dictionary to a list.

Problem: Given a dictionary of key:value pairs. Convert it to a list of (key, value) tuples.

Example: Given the following dictionary.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47}

You want to convert it to a list of (key, value) tuples:

[('Alice', 19), ('Bob', 23), ('Carl', 47)]

You can get a quick overview of the methods examined in this article next:

Exercise: Change the data structure of the dictionary elements. Does it still work?

Let’s dive into the methods!

Method 1: List of Tuples with dict.items() + list()

dict to list python

The first approach uses the dictionary method dict.items() to retrieve an iterable of (key, value) tuples. The only thing left is to convert it to a list using the built-in list() constructor.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 1
t = list(d.items())
print(t)
# [('Alice', 19), ('Bob', 23), ('Carl', 47)]

The variable t now holds a list of (key, value) tuples. Note that in many cases, it’s not necessary to actually convert it to a list, and, thus, instantiate the data structure in memory. For example, if you want to loop over all (key, value) pairs in the dictionary, you can do so without conversion:

for k,v in d.items(): s = str(k) + '->' + str(v) print(s) '''
Alice->19
Bob->23
Carl->47 '''

Using the items() method on the dictionary object is the most Pythonic way if everything you want is to retrieve a list of (key, value) pairs. However, what if you want to get a list of keys—ignoring the values for now?

Method 2: List of Keys with dict.key()

To get a list of key values, use the dict.keys() method and pass the resulting iterable into a list() constructor.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 2
t = list(d.keys())
print(t)
# ['Alice', 'Bob', 'Carl']

Similarly, you may want to get a list of values.

Method 3: List of Values with dict.values()

To get a list of key values, use the dict.values() method and pass the resulting iterable into a list() constructor.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 3
t = list(d.values())
print(t)
# [19, 23, 47]

But what if you want to modify each (key, value) tuple? Let’s study some alternatives.

Method 4: List Comprehension with dict.items()

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 and if statements.

You can use list comprehension to modify each (key, value) pair from the original dictionary before you store the result in the new list.

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 4
t = [(k[:3], v-1) for k, v in d.items()]
print(t)
# [('Ali', 18), ('Bob', 22), ('Car', 46)]

You transform each key to a string with three characters using slicing and reduce each value by one.

Method 5: zip() with dict.keys() and dict.values()

Just for comprehensibility, you could (theoretically) use the zip() function to create a list of tuples:

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 5
t = list(zip(d.keys(), d.values()))
print(t)
# [('Alice', 19), ('Bob', 23), ('Carl', 47)]

However, there’s no benefit compared to just using the dict.items() method. However, I wanted to show you this because the zip() function is frequently used in Python and it’s important for you to understand it.

Method 6: Basic Loop

The last method uses a basic for loop—not the worst way of doing it! Sure, a Python pro would use the most Pythonic ways I’ve shown you above. But using a basic for loop is sometimes superior—especially if you want to be able to customize the code later (e.g., increasing the complexity of the loop body).

d = {'Alice': 19, 'Bob': 23, 'Carl': 47} # Method 6
t = []
for k, v in d.items(): t.append((k,v))
print(t)
# [('Alice', 19), ('Bob', 23), ('Carl', 47)]

A single-line for loop or list comprehension statement is not the most Pythonic way to convert a dictionary to a Python list if you want to modify each new list element using a more complicated body expression. In this case, a straightforward for loop is your best choice!

Related articles:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

The Most Pythonic Way to Compare Two Lists in Python

Problem: Given are two lists l1 and l2. You want to perform either of the following:

  • 1. Boolean Comparison: Compare the lists element-wise and return True if your comparison metric returns True for all pairs of elements, and otherwise False.
  • 2. Difference: Find the difference of elements in the first list but not in the second.

Example: You start with two lists.

l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3] # 1. Boolean Comparison
result = False # 2. Difference
result = [4, 5]

Let’s discuss the most Pythonic ways of accomplishing these problems. We start with five ways to perform the Boolean comparison and look at five ways to perform the simple difference, next.

Boolean Comparison

Short answer: The most Pythonic way to check if two ordered lists l1 and l2 are identical, is to use the l1 == l2 operator for element-wise comparison. If all elements are equal and the length of the lists are the same, the return value is True.

Problem: Given are two lists l1 and l2. You want to perform Boolean Comparison: Compare the lists element-wise and return True if your comparison metric returns True for all pairs of elements, and otherwise False.

Examples:

l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 5, 4]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 4, 5]
# compare(l1, l2) --> True

Let’s discuss the most Pythonic ways of solving this problem. Here’s a quick interactive code overview:

Exercise: Glance over all methods and run the code. What questions come to mind? Do you understand each method?

Read on to learn about each method in detail!

Method 1: Simple Comparison

Not always is the simplest method the best one. But for this particular problem, it is! The equality operator == compares a list element-wise—many Python coders don’t know this!

# 1. Simple Comparison
def method_1(l1, l2): return l1 == l2 l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_1(l1, l2))
# False

So, if you just want to learn about the most Pythonic way to solve this problem, look no further.

But if you want to dive into the wonderful world of Python, learning about different interesting and powerful Python functions, read on!

Method 2: Simple For Loop

The following method is what you’d see from a coder coming from another programming language or from a beginner who doesn’t know about the equality operator on lists (see Method 1).

# 2. Simple For Loop
def method_2(l1, l2): for i in range(min(len(l1), len(l2))): if l1[i] != l2[i]: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_2(l1, l2))
# False

In the code, you iterate over all indices from 0 to the last position of the smallest list as determined by the part min(len(l1), len(l2)). You then check if both elements at the same position are different. If they are different, i.e., l1[i] != l2[i], you can immediately return False because the lists are also different.

If you went through the whole loop without returning False, the list elements are similar. But one list may still be longer! So, by returning len(l1) == len(l2), you ensure to only return True if (1) all elements are equal and (2) the lists have the same length.

A lot of code to accomplish such a simple thing! Let’s see how a better coder would leverage the zip() function to reduce the complexity of the code.

Method 3: zip() + For Loop

The zip function takes a number of iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple for every i.

Let’s see how you can use the function to make the previous code more concise:

# 3. Zip + For Loop
def method_3(l1, l2): for x, y in zip(l1, l2): if x != y: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_3(l1, l2))
# False

Instead of iterating over indices, you now iterate over pairs of elements (the ones zipped together). If the lists have different sizes, the remaining elements from the longer list will be skipped. This way, element-wise comparison becomes simpler and no elaborate indexing schemes are required. Avoiding indices by means of the zip() function is a more Pythonic way for sure!

Method 4: sum() + zip() + len()

But true Python coders will often avoid a for loop and use a generator expression instead.

  • You first create an iterable of Boolean values using the generator expression x == y for x, y in zip(l1, l2).
  • Then, you sum up over the Boolean values (another trick of pro coders) to find the number of elements that are the same and store it in variable num_equal.
  • Finally, you compare this with the length of both lists. If all three values are the same, both lists have the same elements and their length is the same, too. They are equal!
# 4. Sum + Zip + Len
def method_4(l1, l2): num_equal = sum(x == y for x, y in zip(l1, l2)) return num_equal == len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_4(l1, l2))
# False print(method_4([1, 2], [1, 2]))
# True

From the methods except the first one using the == operator, this is the most Pythonic way due to the use of efficient Python helper functions like zip(), len(), and sum() and generator expressions to make the code more concise and more readable.

You could also write this in a single line of code!

sum(x == y for x, y in zip(l1, l2)) == len(l1) == len(l2)

If you love Python one-liners, check out my new book Python One-Liners with internationally renowned publisher NoStarch press. (Amazon Link)

Method 5: map() + reduce() + len()

The last method is just to train your functional programming skills.

# 5. map() + reduce() + len()
from functools import reduce
def method_5(l1, l2): equal = map(lambda x, y: x == y, l1, l2) result = reduce(lambda x, y: x and y, equal) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# True

The map() function combines all pairs of elements to Boolean values (are the two elements equal?). The reduce() function combines all Boolean values performing an and operation. Sure, you can also use the more concise variant using the all() function:

Method 6: map() + all()

This is the same as the previous method—but using the all() function instead of reduce() to combine all Boolean values in a global and operation.

# 6. map() + all()
def method_6(l1, l2): result = all(map(lambda x, y: x == y, l1, l2)) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# True

If you want to learn something new every day, join my free Python email series for continuous improvement in Python and computer science.

Original article: The Most Pythonic Way to Check if Two Ordered Lists Are Identical

Difference

Short answer: The most Pythonic way to compute the difference between two lists l1 and l2 is the list comprehension statement [x for x in l1 if x not in set(l2)]. This works even if you have duplicate list entries, it maintains the original list ordering, and it’s efficient due to the constant runtime complexity of the set membership operation.

What’s the best way to compute the difference between two lists in Python?

a = [5, 4, 3, 2, 1]
b = [4, 5, 6, 7] # a - b == [3, 2, 1]
# b - a == [6, 7]

Let’s have an overview in the following interactive code shell:

Exercise: Run the code and think about your preferred way!

Let’s dive into each of the methods to find the most Pythonic one for your particular scenario.

Method 1: Set Difference

The naive approach to solve this problem is to convert both lists into sets and use the set minus (or set difference) operation.

# Method 1: Set Difference
print(set(a) - set(b))
# {1, 2, 3}
print(set(b) - set(a))
# {6, 7}

This approach is elegant because it’s readable, efficient, and concise.

However, there are some unique properties to this method which you should be aware of:

  • The result is a set and not a list. You can convert it back to a list by using the list(...) constructor.
  • All duplicated list entries are removed in the process because sets cannot have duplicated elements.
  • The order of the original list is lost because sets do not maintain the ordering of the elements.

If all three properties are acceptable to you, this is by far the most efficient approach as evaluated later in this article!

However, how can you maintain the order of the original list elements while also allow duplicates? Let’s dive into the list comprehension alternative!

Method 2: List Comprehension

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 and if statements.

You can use list comprehension to go over all elements in the first list but ignore them if they are in the second list:

# Method 2: List Comprehension
print([x for x in a if x not in set(b)])
# [3, 2, 1]

We used a small but effective optimization of converting the second list b to a set first. The reason is that checking membership x in b is much faster for sets than for lists. However, semantically, both variants are identical.

Here are the distinctive properties of this approach:

  • The result of the list comprehension statement is a list.
  • The order of the original list is maintained.
  • Duplicate elements are maintained.

If you rely on these more powerful guarantees, use the list comprehension approach because it’s the most Pythonic one.

Method 3: Simple For Loop

Surprisingly, some online tutorials recommend using a nested for loop (e.g., those guys):

# Method 3: Nested For Loop
d = []
for x in a: if x not in b: d.append(x)
print(d)
# [3, 2, 1]

In my opinion, this approach would only be used by absolute beginners or coders who come from other programming languages such as C++ or Java and don’t know essential Python features like list comprehension. You can optimize this method by converting the list b to a set first to accelerate the check if x not in b by a significant margin.

Original Article: List Difference | The Most Pythonic Way

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

List Difference | The Most Pythonic Way

Short answer: The most Pythonic way to compute the difference between two lists l1 and l2 is the list comprehension statement [x for x in l1 if x not in set(l2)]. This works even if you have duplicate list entries, it maintains the original list ordering, and it’s efficient due to the constant runtime complexity of the set membership operation.

What’s the best way to compute the difference between two lists in Python?

a = [5, 4, 3, 2, 1]
b = [4, 5, 6, 7] # a - b == [3, 2, 1]
# b - a == [6, 7]

In Python, you always have multiple ways to solve the same (or a similar) problem. Let’s have an overview in the following interactive code shell:

Exercise: Run the code and think about your preferred way!

Let’s dive into each of the methods to find the most Pythonic one for your particular scenario.

Method 1: Set Difference

The naive approach to solve this problem is to convert both lists into sets and use the set minus (or set difference) operation.

# Method 1: Set Difference
print(set(a) - set(b))
# {1, 2, 3}
print(set(b) - set(a))
# {6, 7}

This approach is elegant because it’s readable, efficient, and concise.

However, there are some unique properties to this method which you should be aware of:

  • The result is a set and not a list. You can convert it back to a list by using the list(...) constructor.
  • All duplicated list entries are removed in the process because sets cannot have duplicated elements.
  • The order of the original list is lost because sets do not maintain the ordering of the elements.

If all three properties are acceptable to you, this is by far the most efficient approach as evaluated later in this article!

However, how can you maintain the order of the original list elements while also allow duplicates? Let’s dive into the list comprehension alternative!

Method 2: List Comprehension

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 and if statements.

You can use list comprehension to go over all elements in the first list but ignore them if they are in the second list:

# Method 2: List Comprehension
print([x for x in a if x not in set(b)])
# [3, 2, 1]

We used a small but effective optimization of converting the second list b to a set first. The reason is that checking membership x in b is much faster for sets than for lists. However, semantically, both variants are identical.

Here are the distinctive properties of this approach:

  • The result of the list comprehension statement is a list.
  • The order of the original list is maintained.
  • Duplicate elements are maintained.

If you rely on these more powerful guarantees, use the list comprehension approach because it’s the most Pythonic one.

Method 3: Simple For Loop

Surprisingly, some online tutorials recommend using a nested for loop (e.g., those guys):

# Method 3: Nested For Loop
d = []
for x in a: if x not in b: d.append(x)
print(d)
# [3, 2, 1]

In my opinion, this approach would only be used by absolute beginners or coders who come from other programming languages such as C++ or Java and don’t know essential Python features like list comprehension. You can optimize this method by converting the list b to a set first to accelerate the check if x not in b by a significant margin.

Performance Evaluation

Want to know the most performant one? In the following, I tested three different approaches:

import timeit init = 'l1 = list(range(100)); l2 = list(range(50))' # 1. Set Conversion
print(timeit.timeit('list(set(l1) - set(l2))', init, number = 10000)) # 2. List Comprehension
print(timeit.timeit('[x for x in l1 if x not in l2]', init, number = 10000)) # 3. List Comprehension + set
print(timeit.timeit('s = set(l2);[x for x in l1 if x not in s]', init, number = 10000)) '''
0.1620231000000001
0.5186101000000001
0.057180300000000184 '''

You can run the code in our interactive Python shell:

Exercise: Run the code. Which is fastest and why?

Although the first approach seems to be fastest, you now know that it has some disadvantages, too. (Loses duplicate info, loses ordering info.) From the two list comprehension approaches, the second one kills the first one in terms of runtime complexity and performance!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

The Most Pythonic Way to Remove Multiple Items From a List

Python’s built-in list data structure has many powerful methods any advanced Python programmer must be familiar with. However, some operations on lists can’t be performed simply by calling the right method.

You can add a single item to a list using the method append(item) on the list. If you want to add a list of items to another list, there is the method expand(items) which does the job for you.

The same holds if you want to delete an item from a list, you simply call the method remove(item)and you get the desired outcome.

But, did you ever wonder how to delete a list of items from a given list? Or what if the indices of the items to be deleted were given, how would you do that?

These were the questions I was asking myself in one of my latest hobby projects. Therefore I decided to find out the most Pythonic way to do that.

Problem

Let’s frame our problem like this: Given a list of Task items, how can we remove all items from the list which are marked as done?

Currently the implementation looks as follows:

class Task: def __init__(self, title): self.title = title self.done = False self.done_by = None def is_done(self): return self.done def set_done(self, name): self.done = True self.done_by = name def __repr__(self): state = f'was done by {self.done_by}' if self.done else 'is not done' s = f'Task: {self.title} {state}' return s todo_list = [ Task('Clean House'), Task('Walk Dog'), Task('Buy Bread'), Task('Repair Car'), Task('Plant Tree'), Task('Water Flowers'), Task('Bake Cake')
] todo_list[0].set_done('Bob')
todo_list[2].set_done('Alice')
todo_list[5].set_done('Bob') # print the whole list
print(todo_list)

So, how can we clean up our todo list so that it contains only tasks that have not yet been done?

Solutions

The following solutions can be divided into two groups:

  1. Delete elements of given indices
  2. Delete elements by a certain condition

Any solution of the first type can also be used to delete the elements by a given condition. To accomplish this, all we have to do, is iterate once over the input list, check the condition and store the indices of the elements for which the condition was True. This can be implemented as follows:

indices = []
for idx, task in enumerate(todo_list): if task.is_done(): indices.append(idx)

Since it takes one iteration of the list to find the indices, this adds O(n) to the runtime complexity. Yet, since any solution has at least a time complexity of O(n), we can neglect this first step.

Method 1: Remove a Single Item From the List and Repeat in a Loop

As mentioned before, there are methods to remove a single item from a list, either by value or by index.

Therefore one solution to remove several items is to use a method that removes a single item and executes it in a loop. Though, there is a pitfall to this solution. After we remove the element at index 0, all the other elements shift, and their indices change because the element at index 1 is now at index 0 and so on.

This is how the solution would look as code:

1.1. Remove using pop()

The list.pop() method removes and returns the last element from an existing list. The list.pop(index) method with the optional argument index removes and returns the element at the position index.

indices = [0, 2, 5] # must be ordered!
shift = 0
for i in indices: todo_list.pop(i-shift) shift += 1

Well, probably this looks a bit awkward to you, and be reassured, it’s not the way you would do it in Python!

To avoid shifting, we can reverse sort the list of indices so that we can remove the items from end to start:

indices = [0, 2, 5]
for i in sorted(indices, reverse=True): todo_list.pop(i)

1.2. Remove using remove()

A slightly simpler solution, but still not the best solution, uses the method remove(item).

We iterate over the list and check for each item if it satisfied the condition so that it can be deleted. This solution would look like this:

for task in todo_list: if task.is_done(): todo_list.remove(task)

Be careful if you use remove(item) on a list of simple data types like integers. The function remove() deletes the first occurrence of the given value from the list!

In all of the above solutions, we performed the deletion in-place, which means, we kept the initial instance of the list.

By now you should see, a good solution to the problem is not that obvious.

1.3. Remove using itemgetter() and remove()

If you use the function itemgetter from the module operator there is another interesting solution which is basically an improvement of solution 1.1.

The function itemgetter takes an arbitrary number of indices and returns all the elements from those indices in a tuple. Here is the implementation of the proposed solution:

from operator import itemgetter indices = [0, 2, 5]
for item in (itemgetter(*idx)(todo_list)): xs.remove(item)

But still, the code is more complex than it needs to be.

Method 2. Remove Multiple Items from a List

In the previous solutions, we simply adapted functionality for deleting a single element so that we could use it inside a loop. In this section, we take a look at more Pythonic solutions for the problem.

2.1. Remove all elements from a list

If you want to remove all elements from the list, there is a very simple solution: Use the list class’s method clear(). It removes all elements from the list in-place.

2.2. Remove a slice from a list

If your elements are in a continuous range or if they have a least equal distances from each other a simple way to delete multiple elements from a list is using the keyword del together with slicing.

This could look like this:

del todo_list[1::2]

It deletes the elements in-place, however, it doesn’t help if we want to delete randomly distributed elements from our list.

2.3. Remove randomly distributed elements from a list using set operations

First, we iterate over the list once and extract all items to be deleted. Then, we convert both lists to sets and perform the removal using set operations. This looks as follows:

done = []
for task in todo_list: if task.is_done(): done.append(task) todo_list = list(set(todo_list) - set(done))

Under the hood, a set in Python is a hashmap that allows performing certain operations on sets very fast (O(1)). Unfortunately we have to convert from a list to a set and back, so that we loose the advantage in speed. And again, we end up with an O(n) solution.

Fore more information about the computational complexity of Python operations, check out our detailed article about the topic.

This solution doesn’t work in-place and is a bit difficult to read due to the many conversions between data structures.

2.4. Remove randomly distributed elements from a list using list comprehension

The best way to do this in Python is actually very close to what we saw in the first section of this article where we iterated over the list and removed the elements for which a certain condition was True.

However, in this solution, we will proceed the other way round: We iterate over the old list and create a new list to which we add all the elements that we want to keep. Obviously, we have to create a new list to achieve this, so the solution won’t work in-place.

Python provides just what we need to get the desired result in one single line of code: list comprehensions.

todo_list = [task for task in todo_list if not task.is_done()]

If we assign the result of the list comprehension back to our initial todo_list variable, this variable will now point to a list that contains only tasks that weren’t done yet.

After the above line of code, the memory address to which the variable todo_list points has changed!

However, that’s how you should delete several elements from a list in Python. If you want to do this in-place, there is also a one-line solution to the problem, though, I personally wouldn’t recommend you to use this.

Here is the code:

[todo_list.remove(task) for task in todo_list if task.is_done()]

Be honest, how long did you take to wrap your head around that?

We use a dummy list comprehension in which we delete the selected elements from the initial list, finally we throw away the list comprehension’s resulting list.

So, what we actually do is to abuse the list comprehension to iterate over todo_list and delete items from it.

Conclusion

Depending on the distribution of the items in the list, there are different solutions.

  1. If you want to remove all elements from a list, use the list’s method clear().
  2. If you want to remove a continuous range from the list or if you want to delete items with equal distances between, use slicing with the operator del l[start:stop].
  3. If you want to remove randomly distributed elements, use a list comprehension which selects only the elements you want to keep – this is the solution I recommend.

Obviously, there are more possibilities to solve the problem, yet, the solutions presented in this article are the most common ones and also the easiest to understand. If you find another great solution, feel free to contact us! We would love to see it.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

The Most Pythonic Way to Check if Two Unordered Lists Are Identical

To check if two unordered lists x and y are identical, compare the converted sets with set(x) == set(y). However, this loses all information about duplicated elements. To consider duplicates, compare the sorted lists with sorted(x) == sorted(y). Due to the efficient merge-sort-like implementation of the sorted() function, this is quite fast for almost-sorted lists.

Problem: Given are two lists x and y. You want to return True if both lists contain the same elements, and otherwise False. A variant of this problem is to ignore duplicates (which makes this problem far simpler).

Examples:

x = [1, 2, 3, 4, 5]
y = [1, 2, 3]
# compare(x, y) --> False x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 5, 4]
# compare(x, y) --> True x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
# compare(x, y) --> True

Let’s discuss the most Pythonic ways of solving this problem. Here’s a quick interactive code overview:

Exercise: Glance over all methods and run the code. What questions come to mind? Do you understand each method?

Read on to learn about each method in detail!

Method 1: Set Conversion

This method assumes that you ignore duplicates. So, the lists [1, 1, 1] and [1] are considered to be identical:

###################
# 1. Set Conversion
###################
def method_1(x, y): return set(x) == set(y) print(method_1([1, 2, 3], [1, 2]))
# False print(method_1([1, 2], [2, 1]))
# True

Converting the list to a set has linear runtime complexity. Comparing two sets for equality also has linear runtime complexity (due to the constant runtime complexity of set membership). So, overall, the runtime complexity of this method is linear in the number of elements in the larger list.

However, a set doesn’t contain any information about the number of times each element is represented. To consider this information, you’ll need a multiset data structure.

Method 2: Multiset with Collections Counter

In Python, there are some multiset packages that are capable of considering the number of times each element is represented in the original list. One of them is the collections.Counter class.

###################
# 2. Collections Counter
################### import collections def method_2(x, y): return collections.Counter(x) == collections.Counter(y) print(method_2([1, 1, 1], [1, 1]))
# False print(method_2([1, 2, 3], [2, 1, 3]))
# True

This method is also efficient and it hides implementation details which leads to a higher degree of decoupling in your Python application. However, you may not like that it requires to import another dependency.

Method 3: Sorting

Sorting a list in Python uses a highly efficient algorithm based on mergesort. This means that if the list is “almost” sorted, the sorting routine is very fast. Only in the absolute worst case, the computational complexity is O(n log n) to sort a list.

As soon as both lists are sorted, you can go on and use the element-wise comparison operator x==y to check identity of two ordered lists x and y.

###################
# 3. Sorting
################### def method_3(x, y): return sorted(x) == sorted(y) print(method_2([1, 1, 1], [1, 1]))
# False print(method_2([1, 2, 3], [2, 1, 3]))
# True

Thanks for reading this article! If you want to learn something new every day, join my free Python email series for continuous improvement in Python and computer science.

Related Video

This video is related to the problem: checking if two ordered lists are identical.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

The Most Pythonic Way to Check if Two Ordered Lists Are Identical

The most Pythonic way to check if two ordered lists l1 and l2 are identical, is to use the l1 == l2 operator for element-wise comparison. If all elements are equal and the length of the lists are the same, the return value is True.

Problem: Given are two lists l1 and l2. You want to perform Boolean Comparison: Compare the lists element-wise and return True if your comparison metric returns True for all pairs of elements, and otherwise False.

Examples:

l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 5, 4]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 4, 5]
# compare(l1, l2) --> True

Let’s discuss the most Pythonic ways of solving this problem. Here’s a quick interactive code overview:

Exercise: Glance over all methods and run the code. What questions come to mind? Do you understand each method?

Read on to learn about each method in detail!

Method 1: Simple Comparison

Not always is the simplest method the best one. But for this particular problem, it is! The equality operator == compares a list element-wise—many Python coders don’t know this!

# 1. Simple Comparison
def method_1(l1, l2): return l1 == l2 l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_1(l1, l2))
# False

So, if you just want to learn about the most Pythonic way to solve this problem, look no further.

But if you want to dive into the wonderful world of Python, learning about different interesting and powerful Python functions, read on!

Method 2: Simple For Loop

The following method is what you’d see from a coder coming from another programming language or from a beginner who doesn’t know about the equality operator on lists (see Method 1).

# 2. Simple For Loop
def method_2(l1, l2): for i in range(min(len(l1), len(l2))): if l1[i] != l2[i]: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_2(l1, l2))
# False

In the code, you iterate over all indices from 0 to the last position of the smallest list as determined by the part min(len(l1), len(l2)). You then check if both elements at the same position are different. If they are different, i.e., l1[i] != l2[i], you can immediately return False because the lists are also different.

If you went through the whole loop without returning False, the list elements are similar. But one list may still be longer! So, by returning len(l1) == len(l2), you ensure to only return True if (1) all elements are equal and (2) the lists have the same length.

A lot of code to accomplish such a simple thing! Let’s see how a better coder would leverage the zip() function to reduce the complexity of the code.

Method 3: zip() + For Loop

The zip function takes a number of iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple for every i.

Let’s see how you can use the function to make the previous code more concise:

# 3. Zip + For Loop
def method_3(l1, l2): for x, y in zip(l1, l2): if x != y: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_3(l1, l2))
# False

Instead of iterating over indices, you now iterate over pairs of elements (the ones zipped together). If the lists have different sizes, the remaining elements from the longer list will be skipped. This way, element-wise comparison becomes simpler and no elaborate indexing schemes are required. Avoiding indices by means of the zip() function is a more Pythonic way for sure!

Method 4: sum() + zip() + len()

But true Python coders will often avoid a for loop and use a generator expression instead.

  • You first create an iterable of Boolean values using the generator expression x == y for x, y in zip(l1, l2).
  • Then, you sum up over the Boolean values (another trick of pro coders) to find the number of elements that are the same and store it in variable num_equal.
  • Finally, you compare this with the length of both lists. If all three values are the same, both lists have the same elements and their length is the same, too. They are equal!
# 4. Sum + Zip + Len
def method_4(l1, l2): num_equal = sum(x == y for x, y in zip(l1, l2)) return num_equal == len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_4(l1, l2))
# False print(method_4([1, 2], [1, 2]))
# True

From the methods except the first one using the == operator, this is the most Pythonic way due to the use of efficient Python helper functions like zip(), len(), and sum() and generator expressions to make the code more concise and more readable.

You could also write this in a single line of code!

sum(x == y for x, y in zip(l1, l2)) == len(l1) == len(l2)

If you love Python one-liners, check out my new book Python One-Liners with internationally renowned publisher NoStarch press. (Amazon Link)

Method 5: map() + reduce() + len()

The last method is just to train your functional programming skills.

# 5. map() + reduce() + len()
from functools import reduce
def method_5(l1, l2): equal = map(lambda x, y: x == y, l1, l2) result = reduce(lambda x, y: x and y, equal) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# True

The map() function combines all pairs of elements to Boolean values (are the two elements equal?). The reduce() function combines all Boolean values performing an and operation. Sure, you can also use the more concise variant using the all() function:

Method 6: map() + all()

This is the same as the previous method—but using the all() function instead of reduce() to combine all Boolean values in a global and operation.

# 6. map() + all()
def method_6(l1, l2): result = all(map(lambda x, y: x == y, l1, l2)) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# True

Thanks for reading this article to the end! I hope you learned something new today. If you want to learn something new every day, join my free Python email series for continuous improvement in Python and computer science.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

Convert Tuple to List | The Most Pythonic Way

Answer: The simplest, most straightforward, and most readable way to convert a tuple to a list is Python’s built-in list(tuple) function. You can pass any iterable (such as a tuple, another list, or a set) as an argument into this so-called constructor function and it returns a new list data structure that contains all elements of the iterable.

Converting a tuple to a list seems trivial, I know. But keep reading and I’ll show you surprising ways of handling this problem. I guarantee that you’ll learn a lot of valuable things from the 3-5 minutes you’ll spend reading this tutorial! 🙂

Problem: Given a tuple of elements. Create a new list with the same elements—thereby converting the tuple to a list.

Example: You have the following tuple.

t = (1, 2, 3)

You want to create a new list data structure that contains the same integer elements:

[1, 2, 3]

Let’s have a look at the different ways to convert a tuple to a list—and discuss which is the most Pythonic way in which circumstance.

You can get a quick overview in the following interactive code shell. Explanations for each method follow after that:

Exercise: Run the code. Skim over each method—which one do you like most? Do you understand each of them?

Let’s dive into the six methods.

Method 1: List Constructor

The simplest, most straightforward, and most readable way to convert a tuple to a list is Python’s built-in list(iterable) function. You can pass any iterable (such as a list, a tuple, or a set) as an argument into this so-called constructor function and it returns a new tuple data structure that contains all elements of the iterable.

Convert List to Tuple using tuple()

Here’s an example:

# Method 1: list() constructor
t = (1, 2, 3)
lst = list(t)
print(lst)
# [1, 2, 3]

This is the most Pythonic way if a flat conversion of a single tuple to a list is all you need. But what if you want to convert multiple tuples to a single list?

Method 2: Unpacking

There’s an alternative that works for one or more tuples to convert one or more tuples into a list. This method is equally efficient and it takes less characters than Method 1 (at the costs of readability for beginner coders). Sounds interesting? Let’s dive into unpacking and the asterisk operator!

The asterisk operator * is also called “star operator” and you can use it as a prefix on any tuple (or list). The operator will “unpack” all elements into an outer structure—for example, into an argument lists or into an enclosing container type such as a list or a tuple.

Here’s how it works to unpack all elements of a tuple into an enclosing list—thereby converting the original tuple to a new list.

# Method 2: Unpacking
t = (1, 2, 3)
lst = [*t]
print(lst)
# [1, 2, 3]

You unpack all elements in the tuple t into the outer structure [*t]. The strength of this approach is—despite being even conciser than the standard list(...) function—that you can unpack multiple values into it!

Method 3: Unpacking to Convert Multiple Tuples to a Single List

Let’s have a look at how you’d create a list from multiple tuples:

# Method 3: Unpacking Multiple Tuples
t1 = (1, 2, 3)
t2 = (4, 5, 6)
lst = [*t1, *t2]
print(lst)
# [1, 2, 3, 4, 5, 6]

The expression [*t1, *t2] unpacks all elements in tuples t1 and t2 into the outer list. This allows you to convert multiple tuples to a single list.

Method 4: Generator Expression to Convert Multiple Tuples to List

If you have multiple tuples stored in a list of lists (or list of tuples) and you want to convert them to a single list, you can use a short generator expression statement to go over all inner tuples and over all elements of each inner tuple. Then, you place each of those elements into the list structure:

# Method 4: Generator Expression
ts = ((1, 2), (3, 4), (5, 6, 7))
lst = [x for t in ts for x in t]
print(lst)
# [1, 2, 3, 4, 5, 6, 7]

This is the most Pythonic way to convert a list of tuples (or tuple of tuples) to a tuple. It’s short and efficient and readable. You don’t create any helper data structure that takes space in memory.

But what if you want to save a few more characters?

Method 5: Generator Expression + Unpacking

Okay, you shouldn’t do this last method using the asterisk operator—it’s unreadable—but I couldn’t help including it here:

# Method 5: Generator Expression + Unpacking
t = ((1, 2), (3, 4), (5, 6, 7))
lst = [*(x for t in ts for x in t)]
print(lst)
# [1, 2, 3, 4, 5, 6, 7]

Rather than using the list(...) function to convert the generator expression to a list, you use the [...] helper structure to indicate that it’s a list you want—and unpack all elements from the generator expression into the list. Sure, it’s not very readable—but you could see such a thing in practice (if pro coders want to show off their skills ;)).

Method 6: Simple For Loop

Let’s end this article by showing the simple thing—using a for loop. Doing simple things is an excellent idea in coding. And, while the problem is more elegantly solved in Method 1 (using the list() constructor), using a simple loop to fill an initially empty list is the default strategy.

# Method 6: Simple For Loop
t = (1, 2, 3, 4)
lst = []
for x in t: lst.append(x)
print(lst)
# [1, 2, 3, 4]

To understand how the code works, you can visualize its execution in the interactive memory visualizer:

Exercise: How often is the loop condition checked?

You will see such a simple conversion method in code bases of Python beginners and programmers who switch to Python coming from other programming languages such as Java or C++. It’s readable but it lacks conciseness.

I hope you liked the article! Please find related articles here:

Related articles:

If you want to boost your Python skills, I’ve created an online academy that’s entirely based on email (and it’s free).

Feel free to join our large community of ambitious Python coders and download your free Python resources (PDF cheat sheets).

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Posted on Leave a comment

How to Test Multiple Variables Against a Value in Python?

To test multiple variables x, y, z against a value in Python, use the expression value in {x, y, z}. Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.

Here’s the code:

Exercise: Add a fourth variable and run the modified code!


In this article, you’ll learn about an interesting problem in programming. Interesting because a quick glance could give us a feeling of this problem being simple. However, diving into it can help us learn some fundamentals about Boolean operators and some data types in a way we might not have thought about earlier. In fact, you could find yourself in this situation if you’re a beginner. We will try and explore some solutions to this problem using Python taking into consideration three approaches.

  • The Incorrect Approach
  • The Correct Approach
  • The Best Approach

Let’s see some code walkthrough to understand it.

Doing It The Wrong Way — The Incorrect Approach

Let’s consider the above lines of code. We have three variables, x = 0, y = 1 and z = 3 and want to print a list, “list1” as output which checks at line 9, 11, 13 and 15 respectively, if either of x, y or z equals to 0, 1, 2, or 3 and append to our output list – list1, the values, c, d, e, and f based on the output condition.

Pause for a moment, and observe. What should be the output for the above lines of code? Now run the above code snippet. If you were expecting the output – [‘c’, ‘d’, ‘f’], read along carefully.

Let’s find out what is happening with our code. To understand it clearly, we must appreciate a few things first. The logical operators in Python do not work in a way you would expect them to work in English. For instance, let us look at line 9 of the code snippet.

From Python documentation (Boolean operations), the expression “x or y” first evaluates x. If x is true, its value is returned. Otherwise, y is evaluated, and the resulting value is returned.

The second point to note here is about operator precedence. The “or” operator has lower precedence than “==” operator, and hence equality is evaluated first.

The line number 9 returns “1” (True) as output. So line number 9 and 10 simplifies to:

Similarly, line 11, 13, and 15 each return 1 as output and hence (therefore) “d”, “e” and “f” gets appended to the list. Below code snippet shows the output for all the conditions individually:

Operations and built-in functions that have a Boolean result always return 0 or False for a false and 1 or True for true, unless otherwise stated. Thus our final output to code snippet in fig1 returns [“c”, “d”, “e”, “f”]

Doing It The Right Way — The Correct Approach

Now we build upon our mistakes above and look at a solution that should give us the expected output. Let’s modify the above code snippet a little and see how it changes the expected output:

The difference is evident here as we use the statement “x == 0 or y == 0 or z == 0” instead of “x or y or z == 0”. In this case, each variable here i.e. x, y, z are checked for equivalence one after the other and if the condition satisfies, the corresponding alphabet i.e c, d, e, f is appended to our list 1 respectively. Run the above code and check the output.

Doing It The Better Way: A Better Approach

With Python, we get myriads of collection/sequence data types and some in-built keywords that we can work with. The original idea of different collection/sequence data types and the keywords available for our use is to simplify how we can create a collection/sequence of data and access them based on the problem statement we are dealing with. We will check two data structures – Tuples and Sets, which bring in a good use case for the scenario that we are dealing with.

The “in” keyword can be used along with sequences like lists, sets, and tuples. It returns True or False based on whether the operand on the left is found or not in the sequence. Let’s check out the code snippet below:

Using Tuples to Do it Better:

In this case, we define variables x, y, and z and then check for the specific value membership with tuples in the above case. Hence, on line 9 we check, 0 to be in the tuple (0, 1, 3), which is a membership check, and if the condition is True, we append alphabet “c” to our list1. Then the membership check is done for values 1, 2, and 3, respectively, and based on whether the condition is True or False, the respective alphabet values of “c”, “d”, “e”, “f” are appended to our list1.

To clarify further, on line 9 we get the output as True and hence “c” is appended to list1 whereas, on line 13, where we check for membership of 2 in the tuple (0, 1, 3), the condition is False and hence “e” is not appended to list1.

Using Sets to Do it Better:

Here’s the code for easier copy&pasting:

x = 0
y = 1
z = 3 list1 = [] if 0 in {x, y, z}: list1.append('c')
if 0 in {x, y, z}: list1.append('d')
if 0 in {x, y, z}: list1.append('e')
if 0 in {x, y, z}: list1.append('f') print(list1)
# ['c', 'd', 'e', 'f']

This solution is the same as the above solution with Tuples. The only difference is the data structure that we use here. With this solution we perform membership checks using Sets and based on the condition being True or False, appending the respective alphabet “c”, “d”, “e”, “f” to list1.

I hope this explanation helps. Try and get your hands dirty running the above code snippets, and you will have a better understanding by the time you are done.

Author

This article is contributed by Finxter Abhigyan Ojha. You can find his Upwork profile here.

Posted on Leave a comment

Convert List to Tuple | The Most Pythonic Way

Answer: The simplest, most straightforward, and most readable way to convert a list to a tuple is Python’s built-in tuple(list) function. You can pass any iterable (such as a list, another tuple, or a set) as an argument into this so-called constructor function and it returns a new tuple data structure that contains all elements of the iterable.

Converting a list to a tuple seems trivial, I know. But keep reading and I’ll show you surprising ways of handling this problem. I guarantee that you’ll learn a lot of valuable things from the 3-5 minutes you’ll spend reading this tutorial! 🙂

Problem: Given a list of elements. Create a new tuple with the same elements—thereby converting the list to a tuple.

Example: You have the following list.

lst = [1, 2, 3]

You want to create a new tuple data structure that contains the same integer elements:

(1, 2, 3)

Let’s have a look at the different ways to convert a list to a tuple—and discuss which is the most Pythonic way in which circumstance.

You can get a quick overview in the following interactive code shell. Explanations for each method follow after that:

Exercise: Run the code. Skim over each method—does any of them confuse you?

Method 1: Tuple Constructor

The simplest, most straightforward, and most readable way to convert a list to a tuple is Python’s built-in tuple(iterable) function. You can pass any iterable (such as a list, another tuple, or a set) as an argument into this so-called constructor function and it returns a new tuple data structure that contains all elements of the iterable.

Convert List to Tuple using tuple()

Here’s an example:

lst = [1, 2, 3]
t = tuple(lst)

The result is the following tuple:

print(t)
# (1, 2, 3)

This is the most Pythonic way if a flat conversion of a single list to a tuple is all you need. But what if you want to convert multiple lists to a tuple?

Method 2: Unpacking

There’s an alternative that works for one or more lists. In other words, you can use this general method to convert one or more lists into a tuple. This method is equally efficient and it takes less characters than Method 1 (at the costs of readability for beginner coders). Sounds interesting? Let’s dive into unpacking and the asterisk operator!

The asterisk operator * is also called “star operator” and you can use it as a prefix on any list. The operator will “unpack” all elements of the list into the outer structure—so make sure you call it only within argument lists or within an enclosing container type such as a list or a tuple.

Here’s how it works to unpack all elements of a list into an enclosing tuple—thereby converting the original list to a new tuple.

t = (*lst,)
print(t)
# (1, 2, 3)

You unpack all elements in the lst into the outer structure (*lst,). The outer parentheses with the comma indicate that it’s a tuple and not the parentheses of a simple expression. If you’d forget to add the comma, Python would interpret the expression (*lst) as being a simple precedence relation and it would throw an error because there’s no outer container data structure that “catches” the unpacked elements.

The strength of this approach is—despite being even conciser than the standard tuple(...) function—that you can unpack multiple values into it!

Method 3: Unpacking to Convert Multiple Lists to a Single Tuple

Let’s have a look at how you’d create a tuple from multiple lists:

lst_1 = [1, 2, 3]
lst_2 = [4, 5, 6]
t = (*lst_1, *lst_2)
print(t)
# (1, 2, 3, 4, 5, 6)

The expression (*lst_1, *lst_2) unpacks all elements in lst_1 and lst_2 into the outer tuple structure. This allows you to convert multiple lists to a single tuple.

Method 4: Generator Expression to Convert Multiple Lists to Tuple

If you have multiple lists stored in a list of lists and you want to convert them to a single tuple, you can use a short generator expression statement to go over all inner lists and over all elements of each inner list. Then, you place each of those elements into the tuple structure:

lst = [[1, 2], [3, 4], [5, 6, 7]]
t = tuple(x for l in lst for x in l)
print(t)
# (1, 2, 3, 4, 5, 6, 7)

This is the most Pythonic way to convert a list of lists to a tuple. It’s short and efficient and readable. You don’t create any helper data structure that takes space in memory.

But what if you want to save a few more characters?

Method 5: Generator Expression + Unpacking

Okay, you shouldn’t do this last method using the asterisk operator—it’s unreadable—but I couldn’t help including it here:

lst = [[1, 2], [3, 4], [5, 6, 7]]
t = (*(x for l in lst for x in l),)
print(t)
# (1, 2, 3, 4, 5, 6, 7)

Rather than using the tuple(...) function to convert the generator expression to a tuple, you use the (...,) helper structure to indicate that it’s a tuple you want—and unpack all elements from the generator expression into the tuple. Sure, it’s not very readable—but you could see such a thing in practice (if pro coders want to show off their skills ;)).

Related articles:

I hope you liked the article!

Feel free to join our large community of ambitious Python coders and download your free Python resources (PDF cheat sheets).

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!