Working With Lists
Posted: July 26, 2007
Author: Scott Newman
Category:
Python
Combining Lists Together
I have a function that returned a list of category IDs, and I wanted to add them to a running list of overall category IDs. When I tried to append() the output of that function, I got a list of lists.
If you want to join list items to an existing list, don't try to use append(). If you do, you'll get that list added as a single item of the first list. Example:
mylist = [1,2,3] mylist >> [1,2,3] mylist.append([4,5,6]) mylist >> [1,2,3,[4,5,6]] len(mylist) 4
In this example, if you want a list of six items, use extend() instead of append():
mylist = [1,2,3] mylist >> [1,2,3] mylist.extend([4,5,6]) mylist >> [1,2,3,4,5,6] len(mylist) 6
Sorting Lists
Here's something to remember about sorting lists: the sort() method does not return a value like many Python methods do. Why is that important? Well, if you are trying to keep your code neat and concise, you could run into this:
>> mylist = [10,50,30] >> print mylist.sort() None
You need to call the sort() method by itself:
>> mylist = [10,50,30] >> mylist.sort() >> print mylist [10,30,50]
Filtering Out Unique Elements of a List
Python has a cool method called set() that can filter a list and return only unique elements. I use it all the time to remove duplicate category names from lists. One thing to remember is that set() returns a datatype of 'set', so you must use the list() method to make it a list again:
>> mylist = ['Dog', 'Cat','Hamster','Dog'] >> set(mylist) # Not what we want! set(['Hamster', 'Dog', 'Cat']) >> list(set(mylist)) ['Hamster', 'Dog', 'Cat']
Further Reading
http://diveintopython.org/native_data_types/lists.html#d0e5887

