OKPEDIA PYTHON LISTA EN

How to create a numeric list in Python

To create a numeric list in Python, create an empty list and add the elements via the append method

lista=[ ]
for x in range(i,j):
lista.append(x)

  • The first statement creates an empty list.
  • The second statement defines a loop from i to j.
  • The third statement adds the counter value to the list with each iteration of the loop.

Alternative method

Alternatively, we can use the comprehension technique

lista=[x for x in range(i,j)]

In this more compact form it is not necessary to define an empty list.

The list is defined by a cycle and a formula.

Note. This allows you to create a mathematical sequence. Instead of the argument x, you can insert a formula or a mathematical function in the append method.

Examples

Example 1

Create an empty list in a variable

squares=[]

Define a for loop to iterate through integers 1 through 5.

In each iteration, add the square of the number to the list with the append method.

for x in range(1,6):
squares.append(x**2)

In the append method the formula x ** 2 is defined, that is the power of x.

View the contents of the squares list.

>>> squares
[1, 4, 9, 16, 25]

The squares of the integers from 1 to 5 have been added to the list.

$$ 1^2=2, 2^2=4, 3^2=9, 4^2=16, 5^5=25 $$ È la successione numerica $$ 2,4,9,16,25 $$

Example 2 ( Comprehension )

Create a list with the squares of the natural numbers from 1 to 5 using the comprehension technique.

squares=[x**2 for x in range(1,6)]

In this compact form the formula x ** 2 and the for loop are integrated into the list.

View the contents of the list

>>> squares
[1, 4, 9, 16, 25]

The list lists the squares of the numbers 1 to 5.

https://how.okpedia.org/en/python/how-to-create-a-numeric-list-in-python


Report us an error or send a suggestion to improve this page


Python List


FacebookTwitterLinkedinLinkedin