How to Dynamically Create a List in Python



Python


In this article, we show how to dynamically create a list in Python.

What we are going to do is not dynamically create a list but dynamically create an array first and then convert this array into a list.

Numpy is a very useful module in Python for working with all types of data. It can do very useful things, one of which is create arrays dynamically.

It is then simple to convert this array into a list.

So below we create a simple program which creates a list that has 50 elements from 1 to 50.



So we import numpy as np, in order to dynamically create an array.

We create a variable, array1, which holds the dynamic array that we create.

We create a dynamic array using the np.arange() function. The arange() function accepts 2 parameters. The first is the first element of the array. The second element is the value where you want the array to end. Keep in mind that the first element is included in the array. The last element is not included in the array. So the first element is inclusive and the last element is exclusive. Therefore, 1 will be in the array. 51 will not be included in the array. The array, therefore, geos from 1 to 50.

We then create another list, list1, which converts the array to a list using the list() function in Python.

We then show the contents of the list.

We can see the list of elements from 1 to 50.

So this is one way of creating a dynamic list in Python.

We also create another array, array2, which creates an array that goes from 0 to 50 but only showing the even numbers from this range.

We can then convert this array into a list and show its contents, which shows the even numbers from 0 to 50.

One of the greatest reasons of using the arange function in Python is the dynamic nature of the np.arange() function. It can show all numbers from a certain range that you specify, such as only showing even numbers, odd numbers, or having a certain interval between displayed elements.

We can then easily convert it into a list using the list() function.

And this is how we can dynamically create a list in Python.


Related Resources

How to Extract All Files and Folders from a Zip File in Python
How to Read the Contents of a Zip File in Python


HTML Comment Box is loading comments...