We’ve dealt with strings, we’ve received the t-shirt. Now it’s time to look at another collection style object, the “list”. Python lists are wonderful little creatures that allow us to organize and manipulate data quickly and easily. We have already encountered some lists. When we ran the sorted() function on our string object in the mad libs post, the object that was returned was a list. If you recall, a “string” is a collection of characters. A list, on the other hand is a collection of anything. You can create lists of numbers, lists of strings, lists of custom objects, even lists of lists. You can also make lists of multiple types of objects. So you could have a list with integers, floating point numbers, and strings, etc. Lists also come with lots of built in methods that make using them fast and easy.
Let’s begin by creating a list. List creation is similar to string creation, except that instead of enclosing your list items in quotes, you use the square brackets ‘[‘ and ‘]’ to denote the start and end of your list. Each item you want to put into your list should be separated by commas. Open your interpreter and type:
myList = [‘a’, ‘b’, ‘c’, ‘dog’]
Lists are easy to spot because they will always be enclosed in square brackets. Accessing items in lists uses the same indexing system that strings use. The first item has an index of 0, the second item’s index is 1, etc.
Note that if you check the type of myList using the type() function, it will return 'list'. However, if you check the type of myList[<index>] it will return the type of the item in the list, in our case, a 'string'. This is because the list object is acting as a container for the objects inside. So the list is and object, and the items in the list are also objects. Each object in the list will retain its original properties. Scary and a little confusing, but powerful. See below:
One of the cool things about lists is we can change them without needing to redefine them. For instance, if we create a list and then later on need to add or remove an item we can do that without having to create a new list. There are several ways to add and remove items from lists.
Common methods for adding or removing objects to/from lists | |
Method | Description |
myList.append(<item>) |
The append() method will add an item on to the end of a list. This is a useful function when starting with a blank list and adding items to it.
|
myList.insert(<index>, <item>) | The insert() method allows you to put an item into your list in whatever location you choose. |
myList.remove(<item>) |
The remove() method will remove the specified item from the list. If there is more than one occurrence of the item in your list, the remove() method will remove the first item, and leave the rest.
|
myList.pop() myList.pop(<index>) |
The pop() method will remove the the last item in your list. You can also give an index number to the pop method and it will remove the item at the index number. If no index is given then it will remove the last item in the list.
|
Like I said, there are lots of cool ways to access and manipulate lists; LOTS of ways. I’m going to cover some of the more common methods in this post, and probably mention some of the more obscure methods in later posts. Now that we know how to add and remove items, let’s look at some methods that allow us to play with the data in our lists. For the following examples I am going to define a new object.
testList = [‘hogwarts’, ‘salmon’, ‘alpaca’, 4, ‘cheese’, 2, ‘superman’, ‘cheese’]
Common methods for adding or removing objects to/from lists | |
Method | Description |
testList.reverse() | The reverse() method reverses the order of the list. |
testList.count(<item>) | The count() method counts the number of times the specified <item> occurs in the list. |
testList.sort() | The sort() method orders the items in the list, numerically and/or alphabetically. |
testList.index(<item>) |
The index() method returns the index number for the specified <item>. If there is more than one occurrence of the <item>, then index() will return the index number of the first occurrence.
|
Finally, there are a few more built in python functions that can be used with lists, some of them you’ve seen before when dealing with strings. (I told you there was lots of stuff you can do with them.)
Built-in Python Functions that can be used with lists | |
Function | Description |
len(<list>) | This function works just like it did with strings. The value returned will be an integer that specifies the number of items in the list. |
max(<list>) |
The max() function will return the item in the list with the maximum value. In the case of numbers, the highest number will be returned; for strings, the highest alphabetically ordered string will be returned.
|
min(<list>) | Like the max() function, min() will return the item with the lowest alpha or numeric value. |
sum(<list>) | The sum() function only works with numeric lists. It adds all of the items in the list together and returns the sum. If there are non-numeric items in the list, sum() will error. |
Tuples
I can’t talk about lists without mentioning it’s less popular and underappreciated kid brother, the “tuple”. Tuples are similar to lists in many ways, but different in one very key way. Tuples are unchangeable. Unlike his big, popular, handsome brother, the tuple has no methods for adding or removing elements. Once the tuple is created, he cannot change. The term programmers user for this is “immutable”. Tuples are immutable objects. Immutable is just a fancy and unfriendly way of saying unchangeable. Programming, like most other fields, likes to use jargon that other “outsiders” won’t easily understand.
Tuples and lists look very similar, but you can always spot a tuple because, instead of being enclosed in square brackets ‘[ ]’, the tuple is enclosed in parentheses ‘( )’. Tuples can be created the same way as lists, just enclose the items in ‘( )’ instead of ‘[ ]’.
myList = [‘cheese’, ‘eggs’, “welch’s grape”]myTuple = (‘cheese’, ‘eggs’, “welch’s grape”)
The purpose of the tuple is often difficult to understand for new programmers, especially python programmers. This is because Python, unlike the ‘C’ programming languages, manages memory for you. The reason the tuple exists is that it uses less memory than a list, and it can be accessed faster. So, tuples should be used when you have a constant list of items that won’t require any ‘in-program’ changes. For example, if you want to write a program that sorts items into pre-defined categories, the list of categories should be put into a tuple because the categories will be:
- Defined before hand
- Accessed often
- Not changed during the program’s execution.
So, don’t dismiss tuples, in many situations they can perform better than the bulkier list object. Plus, it’s a fun word to say... tuple. If you start talking about immutable tuples, other programmers will perk up and know that you are a member of the club.
There is a lot more that can (and will) be said about lists, but this should be a good enough primer to get you familiar with their operation. I will probably do a follow up post to this one that has practical applications for the functions that I have mentioned in this post. After that we will discussing ways of comparing data and making decisions within our programs. Stay tuned.
No comments:
Post a Comment