A list is a data structure in Python that can contain multiple elements of any of the other data type. A list is defined with square brackets
[ ] and commas
, between elements.
>>> lst = [ 1, 2, 3 ] >>> type(lst) list >>> lst = [ 1, 5.3, '3rd_Element'] >>> type(lst) list
Individual elements of a list can be accessed or indexed using bracket
[ ] notation. Note that Python lists start with the index zero, not the index 1. For example:
>>> lst = ['statics', 'strengths', 'dynamics'] >>> lst 'statics' >>> lst 'strengths' >>> lst 'dynamics'
: are used inside the square brackets to denote all
>>> lst = [2, 4, 6] >>> lst[:] [2, 4, 6]
Negative numbers can be used as indexes to call the last number of elements in the list
>>> lst = [2, 4, 6] >>> lst[-1] 6
The colon operator can also be used to denote all up to and thru end.
>>> lst = [2, 4, 6] >>> lst[:2] # all up to 2 [2, 4]
>>> lst = [2, 4, 6] >>> lst[2:] # 2 thru end 
The colon operator can also be used to denote start : end + 1. Note that indexing here in not inclusive.
lst[1:3] returns the 2nd element, and 3rd element but not the fourth even though
3 is used in the index.