Lists
Explore the fundamentals of Python lists including creation, indexing, slicing, and various methods to add or remove items. Understand list behavior in boolean contexts and learn techniques to search and modify list contents effectively.
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.
① 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.
① You can get a part of a list, called a “slice”, by specifying two indices. The return value is a new list containing all the items of the list, in order, starting with the first slice index (in this case a_list[1]), up to but not including the second slice index (in this case a_list[3]). ...