List stores multiple values.
There are couple of ways to initialize list:
In this example a list with 3 elements is created.
Size is the count of elements in list.
It's accessed via the len
function.
Output:
List's values can be accessed via indexes starting from 0.
If we declare the following list:
It's elements are:
So if we type the following line:
It will print:
Accessing index outside of the list results in IndexError
.
Let's have a list with 4 elements. If we access the 4th or higher index an exception will be thrown.
Such example is:
Let's have an example in which all elements of list are printed.
Output:
Other way to do it is via for in
.
Elements can be inserted using the append
function.
Let's have a program which fills list with values:
Let's have a program which calculates the product of all even numbers:
Output:
The only even numbers in the list are 2 and 4 which are multiplied.