Tutorial on Python Lists

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

A python list can hold multiple types …

stuff = ['apple', 1, (22.7, 31.5)]

It’s element can be accessed by index …

stuff[2]

Or you can get the index of an element by …

stuff.index(‘apple’)

But you have to make sure “apple” is in the list to begin with. Otherwise, it will throw a ValueError. To check if something is in a list…

if 'apple' in stuff:
stuff.index('apple')

Like string, you can add lists…

my_list = ['apple', 'pear']
your_list = ['banana', 'orange']

new_list = my_list + your_list
# ['apple', 'pear', 'banana', 'orange']

Sorting List

Its elements are ordered. But it can be sorted with the sorted() which will not alter the original list, but return a sorted list. If you have a list of tuples, it will sort first by the first element of the tuple and then on the next element of the tuple. For example…

sorted_list = sorted([('b', 1), ('b', 4), ('a', 7), ('a', 3)])
# [('a', 3), ('a', 7), ('b', 1), ('b', 4)]

The sorted function can also take optional arguments such as “key” (for custom sorting), and “reverse”.

So to do a case-insensitive sort, you can do…

sorted(words, key=str.lower)

Note that the older comparison function “cmp” argument has been removed in Python 3. Also your list needs to be all same type in order for sorted() to run.

The sorted() function does not alter the original list, but returns a new list. The sort() method will alter the original list and returns None. For example,

your_list.sort()

will change your_list and return None.

More List Methods

With the list object, you can …

.append – takes an value to be appended to the list

.pop – take an index and returns the element of that index as well as removing it from the list. If no index specified, it takes the last element.

.extend – takes another list and extends the list with it

.remove – takes the value and looks for it in the list and remove from list. If element is not found, will return ValueError

.insert – for example to insert a value a the head of the list: your_list.insert(0, ‘Cat’)

.clear – removes all elements of a list

.copy – shallow copy of list

.count – number of times this value is found

.reverse – alter the list in-place

.sort – alters the list in-place

Slicing Lists

You can slice lists, just like in strings. The following will clone a list…

cloned_list = my_list[:]

It is similar to …

cloned_list = my_list.copy()

The following will not clone, but have my_list and your_list both point to the same list:

your_list = my_list


Related Posts

Tags

Share This