✒️
Start your developer blog today!
✉️
Questions?
Email me

How to Set Multiple Values of a List in Python

Oct 24, 2020 2 min read

Suppose we want to simultaneously set multiple elements of a Python list.

arr = [0, 0, 0, 0, 0]

Using a for Loop

We could very well use a conventional for loop.

for i in range(0, 3):
  arr[i] = 1
# [1, 1, 1, 0, 0]

Using Slice Assignments

We can also assign a portion of the list to another list.

To obtain a portion of the list, we can use the slice operator.

arr[0:3] = [1] * 3 
# [1, 1, 1, 0, 0]
arr[0:3] = [0 for i in range(3)]
# [0, 0, 0, 0, 0]

Check the Lengths!

Ensure that the length of both lists are equal, or we could end up in one of these situations.

arr[0:3] = [1] * 6
# [1, 1, 1, 1, 1, 1, 0, 0]

The specified portion of the left-hand list will be replaced, but the remainder of the right-hand list will still be inserted.

Watch Out for References

If we want to fill a list with objects, we can do so following the same method. However, these objects are populated in the list by reference.

obj = {'key': 1}
arr[0:3] = [obj] * 3
# [{'key': 1}, {'key': 1}, {'key': 1}, 0, 0]
arr[0]['key'] = 5
# [{'key': 5}, {'key': 5}, {'key': 5}, 0, 0]

We can bypass this complication by forcing a shallow copy of each object using the copy() method.

obj = {'key': 1}
arr[0:3] = [x.copy() for x in [obj] * 3]
arr[0]['key'] = 5
# [{'key': 5}, {'key': 1}, {'key': 1}, 0, 0]