List in Python
3. Lists
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
Like strings (and all other built-in sequence type), lists can be indexed and sliced:
All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:
Lists also support operations like concatenation:
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:
You can also add new items at the end of the list, by using the
append()
method (we will see more about methods later):
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
The built-in function
len()
also applies to lists:
It is possible to nest lists (create lists containing other lists), for example:
Comments
Post a Comment