Understanding the Difference Between List Creation Methods in Python

Elshad Karimov
2 min readSep 4, 2024
Photo by Glenn Carstens-Peters on Unsplash

In senior-level Python interviews, one question that often stumps developers is: What’s the difference between [0] * 3and [0, 0, 0]? Let’s dive into this deceptively simple question.

List Creation Methods

Here are three common ways to create a list in Python:

list1 = [0] * 3
list2 = [0, 0, 0]
list3 = [0 for i in range(3)]

At first glance, all these lists look identical: [0, 0, 0]. But under the hood, they differ in memory usage and performance.

Memory Usage

If you measure the size of these lists using sys.getsizeof(), you’ll notice differences:

import sys
print(sys.getsizeof(list1)) # Output: 80
print(sys.getsizeof(list2)) # Output: 120
print(sys.getsizeof(list3)) # Output: 88

Why the Difference?

To understand why these lists have different sizes, we need to look at the bytecode generated by each method and how Python handles memory allocation.

  1. [0] * 3: This creates a list by repeating a single-element list three times. The memory allocation is exact—just enough to store the three elements, hence the smaller size.

--

--

Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers