Python generate list of numbers with step size
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. Show
In this article, youll learn everything you need to know on how to create Python lists. Table of Contents
Overview Creating a List in PythonThere are many ways of creating a list in Python. Lets get a quick overview in the following table:
You can play with some examples in our interactive Python shell: Exercise: Use list comprehension to create a list of square numbers. Lets dive into some more specific ways to create various forms of lists in Python. BELOW ILL GIVE YOU A PDF CHEAT SHEET OF THE MOST IMPORTANT PYTHON LIST METHODS. So keep reading! Python Create List of SizeProblem: 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 StringsYou 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 NumbersSimply 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 ZerosThis 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 RangeTo 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 100A 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 its excluded from the final series. print(list(range(0, 101))) # [0, 1, ..., 100] print(list(range(101))) # [0, 1, ..., 100]Its actually not necessary to give the default start index 0, so you can just skip it. Python Create List with For LoopTo 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 ListsHowever, theres 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 TuplesA 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 ListTo create an equally spaced list, use the np.linspace() function of the NumPy library. Heres a short tutorial on the matter: Lets get a quick overview first. Lets look at the three most common arguments in more detail first: start, stop and num. Heres what the official NumPy docs has to say: numpy.linspace(start, stop, num=50)Return evenly spaced numbers over a specified interval. Returns numevenly-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]. 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) 10But what if you want to initialize your list with random elements? Python Create List of Random ElementsDo you want to initialize a list with some random numbers? Next, Ill show you four different way of accomplishing thisalong 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: Heres a quick overview on how you can create a list of random numbers:
You can try those yourself in our interactive code shell: Exercise: Change the interval of each method to [0, Python Create List of Lists from ZipShort 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 youre like me, youve often cursed the output of the zip function: first of all, its 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']]Heres 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-zTo 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 DictionariesSay, 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 wont 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 dont point to the same object in memory. This would be the case if youd 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 DataFrameTo 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 ArrayTo 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 CopySurprisingly, even advanced Python coders dont 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. Its a shallow copyyou copy only the object references to the list elements and not the objects themselves. Heres a short example: 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. Heres the syntax: list.copy() Arguments: The method doesnt 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:
Heres 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: Instant PDF Download [100% FREE] You can read more about the list.copy() method in our comprehensive guide on this blog. Python Create List from MapProblem: Given a map object. How to create a list? The answer is straight-forwarduse the list() constructor! Heres an example: lst = [1, 2, 3] m = map(str, lst) print(m) # |