Create lists of numbers efficiently
We have seen in the previous sections what are the lists, how to define and how you can edit them using various functions. When defining a list, we saw that we need to insert a sequence of elements within two square brackets.
Well in Python, there is a function that greatly facilitates the definition of lists, the function range (). In fact, since it is a language that often works for the development of scientific applications, the rapid definition of numerical lists and above all of matrices (lists of lists) must be as easy as ever.
This function allows us to obtain lists of numerical values in a very simple and effective way.
> > > List = List (range (10)) > > > list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
As we can see the range () function has created a list of numbers in sequence from 0 to 9, without having to define them one by one. The call to the list () function is used for casting, which is the conversion of the object returned by range () to a list.
The behavior of the range () function varies as the number of arguments passed in vary.
If this method is called with a single value passed as an argument, this will produce a sequence from 0 to that value.
If we pass two arguments, the first will be the starting value, while the second one is the end.
> > > List (range (4,10)) [4, 5, 6, 7, 8, 9]
If this method is called with three arguments, the first will be the starting value, the second to the end, and the third the interval to be taken between a value and the next one to be included in the list
> > > List (range (4, 12.3)) [4, 7, 10]
⇐ go to Lesson 2.9-functions on lists