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!

Posted on Leave a comment

The Most Pythonic Way to Convert a List to a String

To convert a list lst of strings to a string, use the ''.join(lst) method with an empty separator string between the elements. If you have a list of objects, first convert each element to a string and join the result with the generator expression ''.join(str(x) for x in lst).

Problem: Given a list of elements. How to convert them to a string?

Example: Given the following list of strings.

lst = ['a', 'b', 'c']

You want to convert the list of strings to the following string:

'abc'

What’s the most Pythonic way of converting a list to a string? The answer depends on the nuances.

Here’s a quick overview before we dive into each of the methods:

Exercise: Run the code! What’s the most Pythonic way in your opinion?

Method 1: Join List of Strings

The most straightforward way is to use the string.join(iterable) method that concatenates all values in the iterable (such as a list) using the separator string in between the elements.

lst = ['a', 'b', 'c']
s = ''.join(lst)

The output is the following string:

print(s)
# abc

Due to its conciseness and efficiency, this is the most Pythonic way of converting a list of strings to a string. However, the join() method expects that you pass a list of strings. If you have a list of non-strings, it will throw an error!

Related article: The Ultimate Guide to Python Join

Method 2: Join List of Non-Strings with Generator Expression

So, what to do if you want to convert a list of general objects to a string?

The most Pythonic way to concatenate a list of objects is the expression ''.join(str(x) for x in lst) that converts each object to a string using the built-in str(...) function in a generator expression. You can concatenate the resulting list of strings using the join() method on the empty string as a delimiter. The result is a single string value that’s the concatenation of the objects’ string representations.

lst = [1, 2, 3]
s = ''.join(str(x) for x in lst)
print(s)
# 123

This general method works for all objects (because all objects implement the __str__ method per default). It’s the most Pythonic way of converting a list of non-string

Related article: What’s the most Pythonic way to join a list of objects?

Method 3: String Concatenation with +

Just for the sake of completeness, I want to highlight that you can also concatenate all strings in a list by using the + operator. If you have a list with a few objects, this is a viable option:

lst = ['a', 'b', 'c']
s = lst[0] + lst[1] + lst[2]
print(s)
# abc

This is inefficient because each + operator creates a new string. For n list elements, you create n-1 new strings in memory.

Related article: The + operator for string concatenation.

This must be slightly modified when concatenating a list of objects to a single string:

Method 4: String Concatenation with + and str()

Again, if you have a list of objects, you need to convert each object to a string first:

# Method 4: String Concatenation with + and str()
lst = [1.0, 2.0, 3.0]
s = str(lst[0]) + str(lst[1]) + str(lst[2])
print(s)
# 1.02.03.0

This is very tedious and it deserves to be titled the “least Pythonic way to convert a list to a string”. You should prefer the general Method 2 that’s not only shorter and more efficient, but also more readable and generally applicable.

Method 5: Use Map + Join

The map function allows you to convert each element to a string first. You can then join the strings using the standard string.join() method on the resulting iterable of strings.

lst = [1, 2, 'hello', 3.2]
s = ''.join(map(str, lst))
print(s)
# 12hello3.2

This works beautifully for list of objects as well and it’s quite Pythonic. Many Python coders like this functional style—but I don’t consider it the most Pythonic one. Python code should be readable. Guido van Rossum, Python’s creator, tried to avoid functional programming because he didn’t find it readable compared to list comprehension or its generalization “generator expressions” (see Method 2).

Related Article: The map() function in Python

Method 6: Simple Loop

Let’s see what coders who come from another programming language such as Java would do:

lst = [1, 2, 'hello', 3.2]
s = ''
for x in lst: s += str(x)
print(s)
# 12hello3.2

They’d first create an empty string. Then, they’d add the string representation of each list element to the string until all list elements are added.

This is highly inefficient because of the repeated creation of new strings and it needs three lines instead of one. As it’s often the case in Python, you can avoid loops by using Python’s powerful built-in capabilities.

Related article: Go vs Python

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 a File Exists in Python

The method os.path.exists('file.txt') returns True if the file 'file.txt' exists, and False otherwise. To use it, import the os module first with import os. If you want to check if a file exists at a given path, use the standard path notation '/file/at/path/file.txt' as a prefix.

import os # Check for existing file:
print(os.path.exists('main.py'))
# True # Check for non-existing file:
print(os.path.exists('folder/nonexistent.py'))
# False
The Most Pythonic Way to Check if a File Exists in Python

The web is full of guides that show you “the X most common ways to check if a file exists in Python” (examples: here, here, and here). But when reading over them, I found that it’s hard to extract the precise method—they are far too long and the content is fluffy and lengthy.

If you’re like me, you just want to know the best and most Pythonic way to check if a file exists, right?

In this 2-min tutorial, I’ll give you a to-the-point solution that you can apply right away! So, let’s dive into the precise problem formulation and its most Pythonic way to solve it.

Problem: Given a filename and the path information. Check if a file with the filename exists at a specified path, or not. The return value should be a Boolean value (True, if the file exists, and False otherwise).

Example: Say, you’ve got the following filenames as strings, including path information (as string prefix).

filename_1 = 'file-that-exists.txt'
# Method returns True filename_2 = 'my/directory/non-existing-file.txt' # Method returns False

You want a method that returns True for the first filename (the file that exists) and False for the second filename (the file that doesn’t exist).

Solution: Without further ado, let’s look at the most Pythonic way to check, in your script, if a file exists.

>>> import os
>>> os.path.exists('file-that-exists.txt')
True
>>> os.path.exists('my/directory/non-existing-file.txt')
False

You can try this yourself in our interactive code shell:

Exercise: Run the code. What’s the output? Create the non-existing file so that the second method call returns True!

A Pythonic Excursion

You now know how to check if a file exists (and what’s the most Pythonic way of doing so). But there’s a caveat! You actually shouldn’t do it.

The reason is that you probably use your file existence checking mechanism to do something along those lines (only pseudocode):

# PSEUDOCODE:
if file_exists(): open_file()

The problem is that your Python program doesn’t have exclusive control of the file on your operating system. You don’t know what’s happening between checking if the file exists and opening the file.

In other words: this method is not thread-safe. Multiple threads may access the same file, which can lead to strange behaviors.

For example, your program may find that the file exists. Another thread may then delete the file, so it doesn’t exist anymore. Then, your program executes the second line open_file() working on a non-existent file!

To resolve this issue, you should just open the file right away and enclose it in a try/except block. If the file doesn’t exist, Python throws an exception which you catch in your enclosing block.

try: f = open('file.txt') # Do something with file f.close()
except FileNotFoundError: print('File does not exist')

This is far better—if you want to avoid any output if the file doesn’t exist, just do nothing in the except statement:

try: f = open('nonexistent_file.py') print(f) f.close()
except FileNotFoundError: None

I hope you liked the small tutorial. If you want to improve your Python skills continuously (and for free), check out my email computer science academy (including free 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

string.join(list) vs list.join(string) | Why Python’s Creators Chose The Former

If you’re like me, you may have asked yourself the following question:

Why is it string.join(list) instead of list.join(string) in Python? 🙄

The join method works with any iterable, not just with lists. Therefore, you’d have to implement it in hundreds of classes instead of just one (in the string class). Additionally, join() works only on a string delimiter and with an iterable of strings. Thus, it’s specific to strings and shouldn’t be allowed to be applied on, say, a list of integers.

Let’s divide the world into REALITY and FANTASY.

REALITY: You probably know the string.join(list) method in Python to concatenate all strings in the list using string as a delimiter:

# REALITY:
lst = ['a', 'b', 'c']
print('-'.join(lst))
# a-b-c

FANTASY: Many coders find this confusing, wouldn’t it be more intuitive to use list.join(string) rather than string.join(list)?

# FANTASY WORLD:
lst = ['a', 'b', 'c']
print(lst.join('-'))
# a-b-c

This option of joining a list to a string would feel more object-oriented: you want to join the list and not the string, after all!

So, what are the thought processes behind Python’s creators? Why did they decide to create a join() method on the string rather than the list type?

In this article, I’ve compiled the pro and con arguments from various sources. You can find a detailed list of the sources below.

Argument 1: One Method to Join ‘Em All

You can join any iterable such as a list, tuple, dictionary, or set. But the delimiter must be a string. Thus, you have two options:

  • Require that each iterable implements its own join method (such as __str__).
  • Implement only one join method that works on each iterable.

The latter is far less work for the language creators, and less confusing for the programmer.

# FANTASY WORLD:
['a', 'b', 'c'].join('-')
('a', 'b', 'c').join('-')
{'a', 'b', 'c'}.join('-')
...
# a-b-c

In the fantasy world, you have many implementations of basically the same method.

# FANTASY WORLD:
['a', 'b', 'c'].join('-')
('a', 'b', 'c').join('-')
{'a', 'b', 'c'}.join('-')
...
# a-b-c

This would be confusing as every single iterable must implement the same method. Either there would be a lot of redundant code, or the method must be implemented on the iterable object which leads us to the next argument:

Argument 2: Explicit is Better Than Implicit

If you type into your Python shell the two words import this, it’ll print the “Zen of Python”:

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
...

Go ahead and try it yourself, I’ll wait:

The join() method can only join iterables if they contain strings:

lst = [1, 'b', 'c']
print('-'.join(lst))
# TypeError: sequence item 0: expected str instance, int found

Python will throw a TypeError, if you try to join an iterable that contains at least one non-string element.

Say, we live in FANTASY WORLD and the iterable type implements a join method that’s valid (among others) for all container types such as lists. This would be the only alternative that makes sense and doesn’t add lots of redundant code to the Python library.

This would mean that all iterables containing arbitrary elements could be joined to a string! Even if the elements in the iterable are not of type string. Even if they are absurd data types you created just to confuse Python.

You may ask: so what? But the problem is that Python would have to use an implicit string conversion scheme in case the objects are not of type string. The default string representation is often unreadable or not suitable to appear in a concatenation. Surely, this would add lots and lots of confusion.

For example: what does it, semantically, mean to join a list of integers? Adding them? Concatenating the string representations? Averaging them? There’s no clear answer and any implicit choice would lead to confusion. Explicit is better than implicit!

Note: There’s another problem with implementing a join method on the iterable level! The iterable is not a type but an interface for any type that defines an __iter__ method. Thus, it comes back to requiring all iterables to implement their custom join which is complicated and messy.

Argument 3: Unexpected Dependency of Iterables From String and Unicode

Using list.join() was actually proposed by Skip Montanaro, one of Python’s creators:

On Fri, 11 Jun 1999, Skip Montanaro wrote: It occurred to me just a few minutes after sending my previous message that
it might make sense to make string.join a method for lists and tuples.
They'd obviously have to make the same type checks that string.join does.
as in:
['spam!', 'eggs!'].join() 'spam! eggs!'
?

But David replied that he didn’t like the implications from the generalization of join(): the reduce() function:

I like the notion, but I think it would naturally migrate towards
genericity, at which point it might be called "reduce", so that: ['spam!', 'eggs!'].reduce() 'spam!eggs!' ['spam!', 'eggs!'].reduce(' ') 'spam! eggs!' [1,2,3].reduce()
6 # 1 + 2 + 3 [1,2,3].reduce(10)
26 # 1 + 10 + 2 + 10 + 3 note that string.join(foo) == foo.reduce(' ')
and string.join(foo, '') == foo.reduce()
--david

You can see that this leads to unclear semantics if you have a list of integers. Do we reduce a list of integers by summing them up or concatenating them? What if you pass the value 10 as a separator?

Guido, Python’s benevolent dictator for life, replied (highlights by me):

>>> On Fri, 11 Jun 1999, Skip Montanaro wrote:
>>> It occurred to me just a few minutes after sending my previous message that
>>> it might make sense to make string.join a method for lists and tuples.
>>> They'd obviously have to make the same type checks that string.join does.
>>> as in:
>>> ['spam!', 'eggs!'].join()
>>> 'spam! eggs!' Note that this is not as powerful as string.join(); the latter works
on any sequence, not just on lists and tuples. (Though that may not
be a big deal.) I also find it slightly objectionable that this is a general list
method but only works if the list contains only strings; Dave Ascher's
generalization to reduce() is cute but strikes me are more general
than useful, and the name will forever present a mystery to most
newcomers. Perhaps join() ought to be a built-in function?
--Guido van Rossum (home page: http://www.python.org/~guido/)

To summarize this conversation, Guido had two counter arguments:

  • The join() method works on all iterables and not only on lists and tuples.
  • The method must be a general list method but works only if the list contains strings.

The final note is interesting though: join() could have been built-in function, too!

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!

Sources

I combined web resources, email communications, and my own thoughts to write this comprehensive guide. I’m confident that the tutorial covers the real sources—but we’ll never know for 100%, don’t we?

  1. https://stackoverflow.com/questions/493819/why-is-it-string-joinlist-instead-of-list-joinstring
  2. https://www.edureka.co/community/3899/python-join-why-is-string-join-list-instead-list-join-string
  3. https://www.edureka.co/community/12487/python-join-why-is-string-join-list-instead-list-join-string
  4. https://intellipaat.com/community/225/python-join-why-is-it-string-join-list-instead-of-list-join-string
  5. https://www.wyzant.com/resources/answers/689501/python-join-why-is-it-string-join-list-instead-of-list-join-string
  6. https://www.quora.com/Why-is-it-string-join-list-instead-of-list-join-string
  7. https://mail.python.org/pipermail/python-dev/1999-June/095366.html
Posted on Leave a comment

How to Use Python’s Join() on a List of Objects (Not Strings)?

The most Pythonic way to concatenate a list of objects is the expression ''.join(str(x) for x in lst) that converts each object to a string using the built-in str(...) function in a generator expression. You can concatenate the resulting list of strings using the join() method on the empty string as a delimiter. The result is a single string value that’s the concatenation of the objects’ string representations.

Writing Pythonic code is at the heart of being an effective coder—and if you choose the wrong ways of solving a problem, you’ll open yourself up for criticism and struggles throughout your programming career. So, what’s the most Pythonic way of solving the following problem?

Problem: Given a list of objects. How to concatenate the string representations of those objects?

Example: You have the following list of objects.

class Obj: def __init__(self, val): self.val = val def __str__(self): return str(self.val) lst = [Obj(0), Obj(1), Obj(2), Obj(4)]

You want to obtain the following result of concatenated string representations of the objects in the list.

0124

Want to play? Run the following interactive code shell:

Exercise: Run the interactive code snippet. Which method do you like most?

Method 1: Join + List Comprehension + Str

This method uses three Python features.

First, the string.join(iterable) method expects an iterable of strings as input and concatenates those using the string delimiter. You can read more about the join() function in our ultimate blog guide.

Second, list comprehension is the Pythonic way to create Python lists in a single line. You use the syntax [expression + statement].

  • In the expression, you define how each element should be modified before adding it into a new list.
  • In the statement, you define which elements to modify and add to the list in the first place.

You can read more about list comprehension in the detailed Finxter guide on the topic.

Third, the str(...) function converts any Python object into a string representation. If you define your custom objects, you should overwrite the __str__() method to customize how exactly your objects are represented as strings.

Combining those three features results in the following simple solution to concatenate the string representations of a list of objects.

print(''.join([str(x) for x in lst]))
# 0124

But there’s a slight simplification lurking around. Read on to learn which!

Method 2: Join + Generator Expression + Str

The previous method has shown a quite effective way to concatenate the string representations of some objects using the join() function of Python strings. As the join() function expects a list of strings, you need to convert all objects x into plain strings using the str(x) function.

Concatenate string representations of list of objects with join() function and generator expression.

However, there’s no need to create a separate list in which you store the string representations. Converting one object at a time is enough because the join function needs only an iterable as an input—and not necessarily a Python list. (All Python lists are iterables but not all iterables are Python lists.)

To free up the memory, you can use a generator expression (without the square brackets needed to create a list):

print(''.join(str(x) for x in lst))
# 0124

In contrast to Method 1, this ensures that the original list does not exist in memory twice—once as a list of objects and once as a list of string represenations of those exact objects. Therefore, this method can be considered the most Pythonic one.

Method 3: Join + Generator Expression + Custom String Representation

A slight modification of the previous version is to use your own custom string representation—rather than the one implemented by the __str__ method.

print(''.join(str(x.val) for x in lst))
# 0124

This gives you some flexibility how you can represent each object for your specific application.

Method 4: Join + Map + Lambda

The map() function transforms each tuple into a string value, and the join() method transforms the collection of strings to a single string—using the given delimiter '--'. If you forget to transform each tuple into a string with the map() function, you’ll get a TypeError because the join() method expects a collection of strings.

Lambda functions are anonymous functions that are not defined in the namespace (they have no names). The syntax is: lambda <argument name(s)> : <return expression>. You’ll see an example next, where each function argument is mapped to its string representation.

print(''.join(map(lambda x: str(x), lst)))
# 0124

This method is a more functional programming style—and some Python coders prefer that. However, Python’s creator Guido van Rossum preferred list comprehension over functional programming because of the readability. That’s why Methods 1-3 should be preferred in general.

If you absolutely want to take functional programming, use the next version:

Method 5: Join + Map + Str

There’s no need to use the lambda function to transform each list element to a string representation—if there’s a built-in function that’s already doing exactly this: the str(...) function you’ve already seen!

print(''.join(map(str, lst)))
# 0124

Because of its conciseness and elegance, passing the str function name as a function argument into the map function is the most Pythonic functional way of solving this problem.

Method 6: Simple Loop + Str (Naive)

Sure, you can also solve the problem in a non-Pythonic way by using a simple for loop and build up the string:

s = ''
for x in lst: s += str(x)
print(s)
# 0124

But that’s not only less concise, it’s also less efficient. So, a master coder in Python would never use such a method!

If you want to become a Python master coder, check out my free in-depth Python email course. Join tens of thousands of ambitious Python coders and become a Python master the automatic 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

Python Join List of DataFrames

To join a list of DataFrames, say dfs, use the pandas.concat(dfs) function that merges an arbitrary number of DataFrames to a single one.

When browsing StackOverflow, I recently stumbled upon the following interesting problem. By thinking about solutions to those small data science problems, you can improve your data science skills, so let’s dive into the problem description.

Problem: Given a list of Pandas DataFrames. How to merge them into a single DataFrame?

Example: You have the list of Pandas DataFrames:

df1 = pd.DataFrame({'Alice' : [18, 'scientist', 24000], 'Bob' : [24, 'student', 12000]})
df2 = pd.DataFrame({'Alice' : [19, 'scientist', 25000], 'Bob' : [25, 'student', 11000]})
df3 = pd.DataFrame({'Alice' : [20, 'scientist', 26000], 'Bob' : [26, 'student', 10000]}) # List of DataFrames
dfs = [df1, df2, df3]

Say, you want to get the following DataFrame:

 Alice Bob
0 18 24
1 scientist student
2 24000 12000
0 19 25
1 scientist student
2 25000 11000
0 20 26
1 scientist student
2 26000 10000

You can try the solution quickly in our interactive Python shell:

Exercise: Print the resulting DataFrame. Run the code. Which merging strategy is used?

Method 1: Pandas Concat

This is the easiest and most straightforward way to concatenate multiple DataFrames.

import pandas as pd df1 = pd.DataFrame({'Alice' : [18, 'scientist', 24000], 'Bob' : [24, 'student', 12000]})
df2 = pd.DataFrame({'Alice' : [19, 'scientist', 25000], 'Bob' : [25, 'student', 11000]})
df3 = pd.DataFrame({'Alice' : [20, 'scientist', 26000], 'Bob' : [26, 'student', 10000]}) # list of dataframes
dfs = [df1, df2, df3] df = pd.concat(dfs)

This generates the following output:

print(df) ''' Alice Bob
0 18 24
1 scientist student
2 24000 12000
0 19 25
1 scientist student
2 25000 11000
0 20 26
1 scientist student
2 26000 10000 '''

The resulting DataFrames contains all original data from all three DataFrames.

Method 2: Reduce + DataFrame Merge

The following method uses the reduce function to repeatedly merge together all dictionaries in the list (no matter its size). To merge two dictionaries, the df.merge() method is used. You can use several merging strategies—in the example, you use "outer":

import pandas as pd df1 = pd.DataFrame({'Alice' : [18, 'scientist', 24000], 'Bob' : [24, 'student', 12000]})
df2 = pd.DataFrame({'Alice' : [19, 'scientist', 25000], 'Bob' : [25, 'student', 11000]})
df3 = pd.DataFrame({'Alice' : [20, 'scientist', 26000], 'Bob' : [26, 'student', 10000]}) # list of dataframes
dfs = [df1, df2, df3] # Method 2
from functools import reduce
df = reduce(lambda df1, df2: df1.merge(df2, "outer"), dfs)

This generates the following output:

print(df) ''' Alice Bob
0 18 24
1 scientist student
2 24000 12000
3 19 25
4 25000 11000
5 20 26
6 26000 10000 '''

You can find a discussion of the different merge strategies here. If you’d use the parameter "inner", you’d obtain the following result:

 Alice Bob
0 scientist student

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 Get a List Slice with Arbitrary Indices in Python?

To extract elements with specific indices from a Python list, use slicing list[start:stop:step]. If you cannot use slicing because there’s no pattern in the indices you want to access, use the list comprehension statement [lst[i] for i in indices], assuming your indices are stored in the variable indices.

People always want to know the most Pythonic solution to a given problem. This tutorial shows you the most Pythonic solution(s) to the following problem:

Problem: How to extract elements with specific indices from a Python list?

Example: You’ve got the following elements.

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

You want to create a new list of elements with indices = [0, 2, 6] in the original list:

['a', 'c', 'g']
How to get elements with specific indices from a Python list?

You can get a quick overview of the most Pythonic methods in our interactive Python shell:

Exercise: Run the code shell. Now, try to access the element with index 7 as well in each of the given methods!

Method 1: List Comprehension

A simple, readable, and efficient way is to use list comprehension that’s 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.

Here’s the code that creates a new list that contains the elements at specific indices (e.g., 0, 2, and 6) in the original list:

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = [lst[i] for i in indices]
print(out)
# ['a', 'c', 'g']

In most cases, this will be the best solution because you don’t need any library and it’s still short and readable. However, if you need to do this multiple times, it may be better to import the NumPy library:

Method 2: NumPy Array Indexing

Python’s library for numerical computations, NumPy, is one of the most powerful tools in your toolbelt—especially if you work as a data scientist. Here’s how you can use NumPy to access arbitrary indices, given a sequence of specific indices:

import numpy as np
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a = np.array(lst)
indices = [0, 2, 6] out = a[indices]

The output is:

print(out)
# ['a' 'c' 'g']

You see that NumPy indexing is far more powerful than Python indexing—it allows you to use arbitrary sequences as indices. Especially, if you need to do multiple of those numerical operations, you may want to import the NumPy library once and gain much in readability and conciseness.

Related resources:

Method 3: Itemgetter

The following method can be seen sometimes—using the itemgetter function from the operator module:

from operator import itemgetter
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = list(itemgetter(*indices)(lst))
print(out)
# ['a', 'c', 'g']

The code performs the following steps:

  • Call the itemgetter() function and pass the arguments 0, 2, and 6. We use the asterisk operator * to unpack the values from the indices variable into the itemgetter() function. Learn more about the asterisk operator in our detailed blog article.
  • This returns a new itemgetter function object.
  • Call the new itemgetter function object by passing the original list lst.
  • The new itemgetter function will now get a tuple of the items at positions 0, 2, and 6 in the original list lst.
  • Convert the tuple to a list using the list(...) built-in Python function.

Method 4: Manual Indices

Just for comprehensibility, I also want to point out the “naive” way of accessing a few elements in the original list and put them into a new list:

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
out = [lst[0], lst[2], lst[6]]
print(out)
# ['a', 'c', 'g']

This is a perfectly valid and efficient approach if you have only a few elements to access. For more than, say, five indices, it quickly becomes unhandy though.

Method 5: Simple Loop

Here’s another approach that’s often used by coders who come from other programming languages such as Java or C++: using simple loops.

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = []
for i in indices: out.append(lst[i])
print(out)
# ['a', 'c', 'g']

While there’s nothing wrong with this, it looks somehow “brutal” to an advanced coder. If you’d use this method, it would be like shouting into the world that you’re not a very sophisticated Python coder. 😉

Nothing wrong with that—don’t get me wrong! But if you want to increase your level of sophistication in Python, join my free email academy with many Python email courses that will sharpen your skills! Have I already said that it’s free?

Join Python Email Academy!

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!