idle session
Lists in Python might look like arrays, but they are much more than that: they are full-blown Python collection objects. This means that lists come with ready-to-use functionality in the form of list methods. Let’s get to know some of Python’s list methods. Open up IDLE and follow along with the code entered at the >>> prompt. You should see exactly the same output as shown here. Start by defining a list of names, which you then display on screen using the print() BIF. Then, use the len() BIF to work out how many data items are in the list, before accessing and displaying the value of the second data item: >>> cast = ["Cleese", 'Palin', 'Jones', "Idle"] >>> print(cast) ['Cleese', 'Palin', 'Jones', 'Idle'] >>> print(len(cast)) 4 >>> print(cast[1])
It’s OK to invoke a BIF on . the results of another BIF
Palin
With your list created, you can use list methods to add a single data item to the end of your list (using the
append() method), remove data from the end of your list (with the pop() method), and add a collection of data items to the end of your list (thanks to the extend() method): >>> cast.append("Gilliam") >>> print(cast)
Methods are invoked using the common “.” dot notation.
['Cleese', 'Palin', 'Jones', 'Idle', 'Gilliam'] >>> cast.pop() 'Gilliam' >>> print(cast) ['Cleese', 'Palin', 'Jones', 'Idle']
ted by commas, It’s another list: items separats. surrounded by square bracke
>>> cast.extend(["Gilliam", "Chapman"]) >>> print(cast) ['Cleese', 'Palin', 'Jones', 'Idle', 'Gilliam', 'Chapman']
Finally, find and remove a specific data item from your list (with the remove() method) and then add a data item before a specific slot location (using the insert() method): >>> cast.remove("Chapman") >>> print(cast) ['Cleese', 'Palin', 'Jones', 'Idle', 'Gilliam'] >>> cast.insert(0, "Chapman") >>> print(cast) ['Chapman', 'Cleese', 'Palin', 'Jones', 'Idle', 'Gilliam']
10 Chapter 1
After all that, we end up wit the cast of Monty Python’s h Flying Circus!