Lists
Lists are a mutable sequence of values of any type.
You can have mixed types in a list.
Lists are 0-indexed. Each element in the list can be accessed using bracket notation and its index number.
You can use negative indices to access elements starting from the end
Get the number of elements a list with the len
function
List Methods
Lists have a lot of useful methods. Here are a few:
append
add an element to the end of the list
insert
add an element at the specified position
pop
remove an element at the specified position (last by default)
extend
add elements of an iterable to the end of the list
For more list methods: https://www.w3schools.com/python/python_ref_list.asp
List Operators
The in
membership operator works with lists.
Looping Over Lists
To loop over lists, use a for in
loop
If you need access to the index number, use range
and len
:
or use enumerate
:
Slicing
Python's slice operator :
works with sequence types (strings, lists, tuples, etc.).
The syntax is a[start:stop:step]
, where start is inclusive and stop is not.
start
, stop
, and step
have default values of 0
, the length of the sequence being sliced, and 1
respectively.
Last updated
Was this helpful?