Lists
Lists are Python’s workhorse datatype. When I say “list,” you might be thinking “array whose size I have to declare in advance, that can only contain items of the same type, &c.” Don’t think that. Lists are much cooler than that.
A list in Python is like an array in Perl 5. In Perl 5, variables that store arrays always start with the @ character; in Python, variables can be named anything, and Python keeps track of the datatype internally.
A list in Python is much more than an array in Java (although it can be used as one if that’s really all you want out of life). A better analogy would be to the ArrayList class, which can hold arbitrary objects and can expand dynamically as new items are added.
Creating a list
Creating a list is easy: use square brackets to wrap a comma-separated list of values.
a_list = ['a', 'b', 'mpilgrim', 'z', 'example'] #①print (a_list)#['a', 'b', 'mpilgrim', 'z', 'example']print (a_list[0] ) #②#aprint (a_list[4] ) #③#exampleprint (a_list[-1]) #④#exampleprint (a_list[-3]) #⑤#mpilgrim
① First, you define a list of five items. Note that they retain their original order. This is not an accident. A list is an ordered set of items.
② A list can be used like a zero-based array. The first item of any non-empty list is always a_list[0]
.
③ The last item of this five-item list is a_list[4]
, because lists are always zero-based.
④ A negative index accesses items from the end of the list counting backwards. The last item of any non-empty list is always a_list[-1]
.
⑤ If the negative index is confusing to you, think of it this way: a_list[-n] == a_list[len(a_list) - n]
. So in this list, a_list[-3] == a_list[5 - 3] == a_list[2]
.
Slicing a list
a_list[0] is the first item of a_list.
Once you’ve defined a list, you can get any part of it as a new list. This is called slicing the list.
a_list = ['a', 'b', 'mpilgrim', 'z', 'example']print (a_list)#['a', 'b', 'mpilgrim', 'z', 'example']print (a_list[1:3] ) #①#['b', 'mpilgrim']print (a_list[1:-1]) #②#['b', 'mpilgrim', 'z']print (a_list[0:3] ) #③#['a', 'b', 'mpilgrim']print (a_list[:3]) #④#['a', 'b', 'mpilgrim']print (a_list[3:] ) #⑤#['z', 'example']print (a_list[:] ) #⑥#['a', 'b', 'mpilgrim', 'z', 'example']
① You can get ...