3.1.4.3 Lists - collections of data | Indexing
Accessing list content
Each of the list's elements may be accessed separately. For example, it can be printed:
print(numbers[0]) # accessing the list's first element
Assuming that all of the previous operations have been completed successfully, the snippet will send
111
to the console.
As you can see in the editor, the list may also be printed as a whole - just like here:
print(numbers) # printing the whole list
As you've probably noticed before, Python decorates the output in a way that suggests that all the presented values form a list. The output from the example snippet above looks like this:
[111, 1, 7, 2, 1]
The len() function
The length of a list may vary during execution. New elements may be added to the list, while others may be removed from it. This means that the list is a very dynamic entity.
If you want to check the list's current length, you can use a function named
len()
(its name comes from length).
The function takes the list's name as an argument, and returns the number of elements currently stored inside the list (in other words - the list's length).
Look at the last line of code in the editor, run the program and check what value it will print to the console. Can you guess?
Comments
Post a Comment