How do you change a list value in Python?

Learn how to replace items in a Python list by solving basic algorithms a get ready for your next coding interview

Photo by Martin Woortman on Unsplash.

Update: Many of you contacted me asking for valuable resources to nail Python coding interviews. Below I share 4 courses that I strongly recommend to keep exercising after practicing the algorithms in this post:

  • LeetCode In Python: 50 Algorithms Coding Interview Questions → Best For Coding Rounds Prep!
  • Python advanced Coding Problems (StrataScratch)→ Best platform I found to prepare Python & SQL coding interviews so far! Better and cheaper than LeetCode!
  • Practicing Coding Interview Questions In Python (60+Problems)
  • Python Data Engineering Nanodegree→ High Quality Course If You Have More Time To Commit. **UP TO 75% DISCOUNT ON UDACITY COURSES IN March 2022**

Hope you’ll find them useful too! Now enjoy the article :D

3 Data Engineering Courses To Advance Your Career In 2021

Join the data industry, change role or simply learn cutting-edge technologies by enrolling in Data Engineering…

towardsdatascience.com

Introduction

While preparing for your next Python coding round, you might have noticed that algorithms requiring to manipulate one or more lists appear rather frequently. Sooner or later, you should expect to encounter one of them during your interviews as well.

Algorithms requiring to manipulate one or more lists appear rather frequently. Sooner or later, you should expect to encounter one of them during your interviews as well.

In order to help you in the process of mastering this data structure and improve your coding skills, below I present 4 methods to replace an item in Python lists as well as four simple algorithms for you to test your skills.

Most of the classic interview questions can be solved with multiple approaches, so for each problem, try to come up with your solution first, before looking at the one I provided. Similarly to other skills, algorithmic interview is one area where you can greatly improve with consistent practice.

1. Indexing

The most straightforward way to replace an item in a list is to use indexing, as it allows you to select an item or range of items in an list and then change the value at a specific position, using the assignment operator:

For example let’s suppose you were working with the following list including six integers:

lst = [10, 7, 12, 56, 3, 14]

and you were asked to add 10 to the third integer from the left. Since lists are indexed starting from zero, you could use one of the following syntaxes to change the element with index = 2 that in our case in the number 12:

#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10

Now try to practice this first method solving the following problem:

PROBLEM #1

Given a non-empty list including integers ( between 1 and 9) , treat it as it was representing a non-negative unique integer and increment it by one. Return the updated list.

In the result, the digits has to be stored such that the first digit of the number obtained by the sum, is at the head of the list, and each element in the list contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself.

Note that our input list is made up of four non-negative integers that together represent the integer 9999. This in an edge case, because by adding 1 to this number, you will obtain an integer with 5 digits (instead of the original 4) and a leading 1.

To account for these type of situations, the solution takes advantage of two conditional statements that start evaluating the digits from last to first (using reverse() to flip the order of the indexes). If not equal to 9, ONLY the last digit is incremented by 1 through the now familiar syntax digits += 1 and the amended list is immediately returned, without evaluating the remaining indexes.

Alternatively, if the last digit is a 9, it is replaced by a 0 and the following (second-to-last) digit is evaluated. If this is not equal to 9, then 1 is added and the amended list returned. Otherwise, if each one of following digits is a 9, then the function will return an list with a leading 1 and as many 0s as the number of the elements in the original list.

10 MCQ’s To Practice Before Your Databricks Apache Spark 3.0 Developer Exam

You put the effort. You invested money and time. Now, the exam is close and you only have one attempt…Ready to nail it?

anbento4.medium.com

2. For Loop

In the problem above, the goal was to just replace the last integer in the list, incrementing it by 1, whereas iteration was just used to cover the edge cases.
However, what if we wanted to replace multiple elements in the list at the same time?

In this instances, using a for loop will work fine as it can be employed to iterate over the items of an list. To show how it works, let’s go back to original list and multiply all the integers by 2:

lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)):
lst[i] = lst[i] * 2
print(lst)Output: [20, 14, 24, 112, 6, 28]

The example above was elementary, but what if you were asked to apply a slightly more complex logic while replacing items in a list?

PROBLEM #2

Consider a list of integers. If the number is odd increment it by 1, if it is even increment it by 2.

Note that, instead of

#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
0, this solution uses the
#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
1 method to iterate over all the elements of the list, check if the integers are odd or even - through the modulo operator - and replace them by adding 1 or 2 respectively.

Enumerate is a built-in function in Python and can be used to add an automatic counter while looping through an iterable object. When the optional

#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
2 parameter is not specified, the counter begins from 0, behaving like it was an actual index.

For this reason, it is very common to use

#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
1 to solve algorithms that require you to manipulate a list based on a condition applied to either the index or to (like in this case) the list values.

3. List Comprehensions

The list comprehension syntax is a more elegant method to loop through the elements of a list and apply some form of manipulation. This is because comprehensions allow you to create a new list in-line, making your code appear very clean and compact.

You can convert the for loop in the example above to a comprehension as follows:

lst = [10, 7, 12, 56, 3, 14]lst = [lst[i] * 2 for i in range(len(lst))]print(lst)Output: [20, 14, 24, 112, 6, 28]

In order to populate the new list, you are also allowed to specify basic conditions as part of list comprehension syntax. This is exactly what you’ll need to do to solve the following algorithm:

PROBLEM #3

Given a list of integers, sorted in ascending order, return a list also sorted in ascending order including:
- the square of the integer, if divisible by 3
- the original integer, if not divisible by 3

In this case, the if condition is specified before the

#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
4 because of the presence of an
#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
5 statement. However when the
#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
5 is not required, you can simply follow the syntax:

output = [ expression for element in list_1 if condition ]
4. Slicing & Shuffling

At times, in coding interviews, you could be asked to re-arrange the items in a list so that they appear in a different order. This can be achieved through slicing and shuffling.

For example if you wished to swap the first 3 and last 3 elements in your initial list, you could write:

lst = [10, 7, 12, 56, 3, 14]lst = lst[3:] + lst[:3]print(lst)Output: [56, 3, 14, 10, 7,
12]

Perhaps, in this case, talking about a replacement is a bit of a stretch as you are in fact just changing the elements’ position in the list. Nonetheless, this method is quite effective and could help you solve the following problem.

PROBLEM #4

Given the list of nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn]. Return the array in the form [x1,y1,x2,y2,…,xn,yn].

The exercise provides you with the index to use for slicing (in this case

#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
7) and requires you to shuffle the input list, by creating new integer pairs.

The integers belonging to each pair, should be the ones sharing the same index, if we sliced the original list in two sub-lists(

#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
8 and
#Option 1
lst[2]= lst[2] + 10
#Option 2
lst[2]+= 10 #no need to repeat "lst[2]" then more elegant
#Option 3
lst[2] = 22 #that is 12 + 10
9) This result can easily be achieved using
lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)):
lst[i] = lst[i] * 2
print(lst)Output: [20, 14, 24, 112, 6, 28]
0 to pair together the elements included in the sub-lists and recursively add them to a new
lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)):
lst[i] = lst[i] * 2
print(lst)Output: [20, 14, 24, 112, 6, 28]
1 list.

Conclusion

In this article, I walked you through 4 methods to replace items in a Python list that are indexing, for loops, list comprehensions and slicing-shuffling.

Each operation is straightforward per se, but you should be able to master them by choosing the most appropriate and efficient method while solving more complex challenges, in preparation for your next coding round.

For this reason, I also presented and shared the solution of 4 algorithms (one for each method) that are representative of the level of complexity you will find while interviewing for junior and mid-level data roles.

Also note that the problems presented in this post are slight reinterpretations of problems available on Leetcode. Each problem admits multiple solutions, therefore mines are just indicative ones.

A Note For My Readers

This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase.