Javascript required
Skip to content Skip to sidebar Skip to footer

How to Make a List of Numbers in Python

Definition Lists: A Python list is an ordered sequence of arbitrary Python objects. It is a mutable object by itself so, unlike Python sets, you can modify a Python list.

In this article, you'll learn everything you need to know on how to create Python lists.

Overview — Creating a List in Python

There are many ways of creating a list in Python. Let's get a quick overview in the following table:

Code Description
[] Square bracket: Initializes an empty list with zero elements. You can add elements later.
[x1, x2, x3, … ] List display: Initializes an empty list with elements x1, x2, x3, … For example, [1, 2, 3] creates a list with three integers 1, 2, and 3.
[expr1, expr2, ... ] List display with expressions: Initializes a list with the result of the expressions expr1, expr2, … For example, [1+1, 2-1] creates the list [2, 1].
[expr for var in iter] List comprehension: applies the expression expr to each element in an iterable.
list(iterable) List constructor that takes an iterable as input and returns a new list.
[x1, x2, ...] * n List multiplication creates a list of n concatenations of the list object. For example [1, 2] * 2 == [1, 2, 1, 2].

You can play with some examples in our interactive Python shell:

Exercise: Use list comprehension to create a list of square numbers.

Let's dive into some more specific ways to create various forms of lists in Python.

BELOW I'LL GIVE YOU A PDF CHEAT SHEET OF THE MOST IMPORTANT PYTHON LIST METHODS. So keep reading!

Python Create List of Size

Problem: Given an integer n. How to initialize a list with n placeholder elements?

# n=0 --> [] # n=1 --> [None] # n=5 --> [None, None, None, None, None]

Solution: Use the list concatenation operation *.

n = 5 lst = [None] * n print(lst) # [None, None, None, None, None]

You can modify the element n as you like. For a detailed discussion on this topic, please visit my blog tutorial on How to Create a List with a Specific Size n? The tutorial also contains many visualizations to teach you the ins and outs of this method (and gives you some powerful alternatives).

Python Create List of Strings

You can use the previous method to create a list of n strings:

n = 3 lst = ['xyz'] * n print(lst) # ['xyz', 'xyz', 'xyz']

But do you want to create a list of numbers?

Python Create List of Numbers

Simply replace the default strings with the default numbers:

n = 3 lst = [1] * n print(lst) # [1, 1, 1]

A special case is the number:

Python Create List of Zeros

This creates a list of zeros:

n = 3 lst = [0] * n print(lst) # [0, 0, 0]

But what if you want to create a list of consecutive numbers 0, 1, 2, …?

Python Create List from Range

To create a list of consecutive numbers from x to y, use the range(x, y) built-in Python function. This only returns a range object which is an iterable. But you can convert the iterable to a list using the list(...) constructor:

print(list(range(2, 4))) # [2, 3]  print(list(range(2, 6))) # [2, 3, 4, 5]  print(list(range(2, 10, 2))) # [2, 4, 6, 8]

You can see that the second argument (the stop index) is not included in the range sequence. The third argument of the range(start, stop, step) function is the optional step size that allows you to skip step numbers of the series of continuous numbers.

Python Create List from 0 to 100

A special situation arises if you want to create a list from 0 to 100 (included). In this case, you simply use the list(range(0, 101)) function call. As stop argument, you use the number 101 because it's excluded from the final series.

print(list(range(0, 101))) # [0, 1, ..., 100]  print(list(range(101))) # [0, 1, ..., 100]

It's actually not necessary to give the default start index 0, so you can just skip it.

Python Create List with For Loop

To create a list with a for loop, you first initialize the empty list, and then subsequently append an element to the list:

lst = [] for x in range(10):     # Append any initial element here:     lst.append(x)  print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can learn more about the single-line for loop in this article.

Python Create List of Lists

However, there's a small problem if you want to create a list with mutable objects (such as a list of lists):

lst = [[]] * n print(lst) # [[], [], [], [], []]  lst[2].append(42)  print(lst) # [[42], [42], [42], [42], [42]]

Changing one list element changes all list elements because all list elements refer to the same list object in memory:

The solution is to use list comprehension (see my detailed blog tutorial on list comprehension for a complete guide):

lst = [[] for _ in range(n)] print(lst) # [[], [], [], [], []]  lst[2].append(42) print(lst) # [[], [], [42], [], []]

In the following visualization, you can see how each element now refers to an independent list object in memory:

Exercise: Run the visualization and convince yourself that only one element is modified! Why is this the case?

Python Create List of Tuples

A similar approach can be used to create a list of tuples instead of a list of lists.

n = 5 lst = [() for _ in range(n)] print(lst)  lst[2] = (1, 2, 3) print(lst)  ''' [(), (), (), (), ()] [(), (), (1, 2, 3), (), ()] '''

You first initialize the list with empty tuples. Tuples are immutable so you cannot change them. But you can overwrite each list element with a new tuple like you did in the example with the third element and tuple (1, 2, 3).

Python Create Equally Spaced List

To create an equally spaced list, use the np.linspace() function of the NumPy library. Here's a short tutorial on the matter:

Let's get a quick overview first.

NumPy np.linspace()

Let's look at the three most common arguments in more detail first: start, stop and num. Here's what the official NumPy docs has to say:

numpy.linspace(start, stop, num=50)

Return evenly spaced numbers over a specified interval. Returns num evenly-spaced samples. The endpoint of the interval can optionally be excluded.

Note: as the name suggests, np.linspace returns numbers that are linearly-spaced apart. Thus they are all the same distance apart from one another (think of points on a line).

From the definition, it follows that np.linspace(-3, 3) will give us 50 numbers evenly spaced apart in the interval [-3, 3].
Let's check this with some code.

Try it yourself: You can run the code in the shell by clicking "Run"!

Exercise: Can you reduce the number of samples to 10?

>>> A = np.linspace(-3, 3)  >>> type(A) numpy.ndarray  # Number of elements in A >>> len(A) 50  # First element of A >>> A[0] -3.0  # Last element of A >>> A[-1] 3.0  # The difference between every value is the same: 0.12244898 >>> np.diff(A) array([0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898, 0.12244898,        0.12244898, 0.12244898, 0.12244898, 0.12244898])

If we want only 10 samples between -3 and 3, we set num=10.

>>> B = np.linspace(-3, 3, num=10)  # B only contains 10 elements now >>> len(B) 10

But what if you want to initialize your list with random elements?

Python Create List of Random Elements

Do you want to initialize a list with some random numbers? Next, I'll show you four different way of accomplishing this—along with a short discussion about "the most Pythonic way".

Problem: Given an integer n. Create a list of n elements in a certain interval (example interval: [0, 20]).

# n = 5 --> [2, 3, 1, 4, 3] # n = 3 --> [10, 12, 1] # n = 10 --> [8, 2, 18, 10, 4, 19, 5, 9, 8, 1]

Solution: Here's a quick overview on how you can create a list of random numbers:

  • Method 1: [random.random() for _ in range(10)] to create a list of random floats.
  • Method 2: [random.randint(0, 999) for _ in range(10)] to create a list of random ints.
  • Method 3: randlist = []; for _ in range(10): randlist.append(random.randint(0, 99)) to create a list of random ints.
  • Method 4: randlist = random.sample(range(20), 10) to create a list of random ints.

You can try those yourself in our interactive code shell:

Exercise: Change the interval of each method to [0, <your age>] and run the code.

Python Create List of Lists from Zip

Short answer: Per default, the zip() function returns a zip object of tuples. To obtain a list of lists as an output, use the list comprehension statement [list(x) for x in zip(l1, l2)] that converts each tuple to a list and stores the converted lists in a new nested list object.

Intermediate Python coders know the zip() function. But if you're like me, you've often cursed the output of the zip function: first of all, it's a zip object (and not a list), and, second, the individual zipped elements are tuples. But what if you need a list of lists as output?

Problem: Given a number of lists l1, l2, .... How ot zip the i-th elements of those lists together and obtain a list of lists?

Example: Given two lists [1, 2, 3, 4] and ['Alice', 'Bob', 'Ann', 'Liz'] and you want the list of lists [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']].

l1 = [1, 2, 3, 4] l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # ... calculate result ... # Output: [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

Here's a quick overview of our solutions:

Exercise: Create a new list l3 and change the four methods to zip together all three lists (instead of only two).

Python Create List a-z

To create a list with all characters 'a', 'b', …, 'z', you can use the list() constructor on the string.ascii_lowercase variable:

>>> import string >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' >>> list(string.ascii_lowercase) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

The list() constructor creates a new list and place all elements in the iterable into the new list. A string is an iterable with character elements. Thus, the result is a list of lowercase characters.

Python Create List of Dictionaries

Say, you have a dictionary {0: 'Alice', 1: 'Bob'} and you want to create a list of dictionaries with copies of the original dictionary: [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}].

d = {0: 'Alice', 1: 'Bob'}  dicts = [{**d} for _ in range(3)] print(dicts) # [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

You use list comprehension with a "throw-away" loop variable underscore _ to create a list of 3 elements. You can change the value 3 if you need more or fewer elements in your list.

The expression {**d} unpacks all (key, value) pairs from the original dictionary d into a new dictionary.

The resulting list contains copies of the original dictionary. If you change one, the others won't see that change:

dicts[0][2] = 'Frank' print(dicts) # [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

Only the first dictionary in the list contains the new key value pair (2: 'Frank') which proves that the dictionaries don't point to the same object in memory. This would be the case if you'd use the following method of copying a list with a single dictionary:

d2 = {0: 'Alice', 1: 'Bob'}  dicts2 = [d2] * 3 print(dicts2) # [{0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}, {0: 'Alice', 1: 'Bob'}]

The method looks right but all three dictionaries are essentially the same:

dicts2[0][2] = 'Frank' print(dicts2) # [{0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}, {0: 'Alice', 1: 'Bob', 2: 'Frank'}]        

If you change one, you change all.

You can see this effect yourself in the following memory visualizer tool:

Exercise: change the method to the correct one so that the change affects only the first dictionary!

Python Create List from DataFrame

To create a list from a Pandas DataFrame, use the method df.values.tolist() on your DataFrame object df:

import pandas as pd  incomes = {'Name': ['Alice','Bob','Ann'],            'Income': [2000, 3000, 9000]}  df = pd.DataFrame(incomes)  lst = df.values.tolist() print(lst) # [['Alice', 2000], ['Bob', 3000], ['Ann', 9000]]

You can see that the output is a list of lists in this example. If you need to improve your Pandas skills, check out the most beautiful Python Pandas Cheat Sheets.

Python Create List from NumPy Array

To convert a NumPy array a to a list, use the a.tolist() method on the array object. If the NumPy array is multi-dimensional, a nested list is created:

import numpy as np  a = np.array([[1, 2, 3],               [4, 5, 6]])  l = a.tolist() print(l) # [[1, 2, 3], [4, 5, 6]]

The resulting list is a nested list of lists.

Python Create List Copy

Surprisingly, even advanced Python coders don't know the details of the copy() method of Python lists. Time to change that!

Definition and Usage: The list.copy() method copies all list elements into a new list. The new list is the return value of the method. It's a shallow copy—you copy only the object references to the list elements and not the objects themselves.

Here's a short example:

>>> lst = [1, 2, 3] >>> lst.copy() [1, 2, 3]

In the first line, you create the list lst consisting of three integers. You then create a new list by copying all elements.

Puzzle – Try It Yourself:

Syntax: You can call this method on each list object in Python. Here's the syntax:

list.copy()

Arguments: The method doesn't take any argument.

Return value: The method list.clear() returns a list object by copying references to all objects in the original list.

Video:

Related articles:

  • The Ultimate Guide to Python Lists

Here's your free PDF cheat sheet showing you all Python list methods on one simple page. Click the image to download the high-resolution PDF file, print it, and post it to your office wall:

You can read more about the list.copy() method in our comprehensive guide on this blog.

Python Create List from Map

Problem: Given a map object. How to create a list?

The answer is straight-forward—use the list() constructor! Here's an example:

lst = [1, 2, 3]  m = map(str, lst) print(m) # <map object at 0x000001E71198B438>  l = list(m) print(l) # ['1', '2', '3']

The resulting list is a list of strings and it contains all elements in the map iterable m.

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!

How to Make a List of Numbers in Python

Source: https://blog.finxter.com/how-to-create-a-python-list/