The world’s leading publication for data science, AI, and ML professionals.

20 Newbie Mistakes that Even Skilled Python Programmers Make

A collection of common mistakes that you should avoid while coding in Python

The best thing about programming (not just in Python but any programming language) is that, typically, there are multiple ways to implement the same solution.

Some ways are, of course, better than others, which may be due to various reasons like:

  • Less memory usage
  • Run-time efficient
  • Fewer lines of code
  • Easy to understand
  • Simple logic, etc.

In this post, I will introduce you to 20 specific situations where Python programmers unknowingly fall into the trap of writing a large, non-elegant, and complex Python code – that eventually holds them back from unleashing the true potential of Python.

Alongside this, I will also provide an alternative solution to the problems proposed that will assist you in correcting those blunders.

You can find the code for this article here.

Let’s begin 🚀 !


1 Using Multiple Print Statements

Naive Approach

If you want to print multiple variables, then the naive approach suggests that each variable should get its own print() statement.

Elegant Approach

As per my experience, using multiple print statements is typically the most commonplace mistake coders (especially newbies) make while coding in Python.

However, what they don’t know is that with print(), you can print multiple variables in a single print statement as follows:

The sep argument above specifies the separator between the various variables printed using the same print statement (a, b and c above).

Note that the end argument is used to specify the ending character of the print statement.

In the code above, end='n---n' parameter prints the new line character, followed by ---, and further, a new line character.

2 Printing the same variable using a FOR loop

Naive Approach

As the title suggests, the objective is to print the same variable multiple times.

Of course, you should create a FOR loop and iterate the number of times you wish to print the variable, right? I mean, what is wrong with that?

Elegant Approach

Although writing a FOR loop has no harm, and everything works fine, it is unnecessary to write a FOR loop to print the same variable multiple times.

3–4 Creating a separate variable to track the index in a loop

Naive Approach – 1

To achieve this, typically, one would define a new variable (idx) to keep track of the index value and increment it with each iteration, as shown below:

Naive Approach – 2

If not the above method, folks would create a range iterator to keep track of the index, as shown in the code below:

Elegant Approach

Thanks to the developer who developed the enumerate() method.

Essentially, with this method, you can track both the index (idx) and the value (i) as follows:

5 Converting a list to a string using FOR loop

Naive Approach

Using a FOR loop, as demonstrated below, we can collect the elements of the list one at a time.

Elegant Approach

The sleeky way of converting a list to a string is using the join() method, as shown below:

Not only does this save you from writing some unnecessary long code, but it is also as intuitive as the for-loop approach.

6 Removing duplicates from a list using a FOR loop

Naive Approach

FOR-loop to the rescue yet again!

The naive approach is to iterate over the input list and store unique elements in a new list.

Elegant Approach

However, removing duplicates from a list is possible with a single line of Python code, as shown below:

The above returns a set, and you can obtain a list as follows:

7 Searching for an element in a list using FOR loop

Naive Approach

Say you want to know whether an element exists in a list (or set) or not and return a boolean response (True if it exists, otherwise False).

The naive approach is demonstrated below:

Ugh! Too much code, isn’t it?

Elegant Approach

Let’s bring that down to a single-line implementation using the in keyword:

8 Iterating over two iterables of the same size using an index variable

Naive Approach

Similar to what we did in Section #3-4, that is, defining a variable specifically for the index, the naive way here would be to adopt the same here, as shown below:

Elegant Approach

The savvy way is to use the zip() function, that pairs corresponding values in two iterables.

9 Reversing a list using a FOR loop

Naive Approach

As you may have guessed, we can reverse iterate over the list and append the elements to a new list, as demonstrated below:

Elegant Approach

If you understand slicing in Python, the elegant solution is just a simple one-liner here:

NO FOR LOOPS!

10 Checking Palindrome using a FOR loop

Naive Approach

Expanding on the idea of the above situation (#9 – reversing a list), we can check if the reversed list is the same as the input list.

Elegant Approach

The elegant approach, as discussed above, is to use slicing and compare it with the input list:

11 Counting the occurrence of an element in an iterable using FOR loop

Naive Approach

The naive approach to finding the frequency of an element is iterating over the list using a FOR loop and counting the number of occurrences.

Elegant Approach

The elegant approach in this case that saves us from writing a FOR loop (yet again) is using the count() method:

You can use the count() method on a string input as well:

12 Obtaining a string’s substring using FOR loop

Naive Approach

The objective here is to return a substring of length n_chars, starting as position start_index.

A newbie’s approach to this problem is using a FOR loop, as demonstrated below:

Elegant Approach

The one-liner approach, however, is to use slicing, which saves you from writing a FOR loop.

13 Defining long integer constants

Imagine you want to declare an integer variable with the value 10²¹.

Naive Approach

Ideally, one would write zeros in successions and count as they are typing.

But say someone else wants to refer to this code. Wouldn’t it be a trouble for them to count all the zeros?

Elegant Approach

To improve the readability, you can separate a group of zeros with _ (underscore), as shown below:

But that still is a hassle, isn’t it? Why should anyone be counting zeros?

If the number is expressible in the form a^b, you should use the pow() method instead.

14 Swapping case of a String with IF conditions

Given a string, the objective is to make uppercase letters lowercase and vice versa.

Naive Approach

A naive approach would involve checking the case of every element and then having specific conditions for each case.

There’s nothing wrong with the output, but why would you do that?

Elegant Approach

Use the swapcase() method instead.

15 Obtaining a Union of two sets

Naive Approach

Iterate over the two sets and add the elements to a new set.

Too many lines of code, isn’t it?

Let’s bring it down to a single line.

Elegant Approach

The set data structure in Python provides a union() method to the union of two sets.

What’s more, you can extend it to any number of input sets:

Isn’t that cool? Imagine how many FOR loops you would have written to merge the four sets.

16 Obtaining the Intersection of two sets

Naive Approach

Similar to the union case discussed above, we can find the common elements between the two sets as follows:

Elegant Approach

However, you can use the intersection() method to achieve the same:

17 Writing Multiple Conditions in an IF statement

To elaborate on this, say you want to implement the following logic. The input is an integer a.

Naive Approach

Here, one would use multiple OR separated conditionals to implement the above logic.

Elegant Approach

An intelligent way to avoid multiple conditionals is by using the in keyword, as demonstrated below:

18 Changing the data type of all elements in a list

Given a list of strings representing integers, the objective is to convert them to a list of integers by changing the data type.

Naive Approach

Iterate over the list using a FOR loop and type-cast individual elements.

Elegant Approach

A smart approach is to use map(), as demonstrated below:

As its first argument, the map() method accepts a function (int) and the second argument is an iterable (input_list).

19 Swapping variables

Given two variables, the objective is to transfer the value in the first variable to the second and that in the second to the first.

Naive Approach

The approach most C/C++ programmers take here is defining a new variable (temp), and they typically extend that in Python too.

Elegant Approach

Fortunately, Python allows multiple assignments in a single statement, eliminating the need for any temporary variable.

20 Generating all combinations of two lists using nested loops

Given two lists (a with length n, and b with length m), generate all nxm combinations.

Naive Approach

Write two nested FOR loops and append all combinations to a list.

Elegant Approach

The elegant way is to use the product() method from the itertools library, as demonstrated below:


Conclusion

To conclude, in this post, I demonstrated 20 different scenarios that I believe most Python programmers have been through and may have possibly taken the wrong approach towards coding the solution.

If you noticed, in most situations, the elegant approach primarily focused on eliminating the explicit coding of the FOR loop used in the former approach.

As a key takeaway from this post, you should always remember that in most cases, the first solution you will come up with will not be an ideal approach. Therefore, a quick Google search will always be beneficial :).

That is why adopting the imperfectionist’s mindset is crucial to becoming an elegant programmer (not just in Python but in any language for that sake).

P.S. I will release the part two of this post soon!

As always, thanks for reading!


🧑‍💻 Become a Data Science PRO! Get the FREE Data Science Mastery Toolkit with 450+ Pandas, NumPy, and SQL questions.

✉️ Sign-up to my Email list to never miss another article on data science guides, tricks and tips, Machine Learning, SQL, Python, and more. Medium will deliver my next articles right to your inbox.


Related Articles

Some areas of this page may shift around if you resize the browser window. Be sure to check heading and document order.