5 Python5 Lists
5 Python5 Lists
• Just like strings, we can get at any single element in a list using an
index specified in square brackets
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>>
http://docs.python.org/tutorial/datastructures.html
Building a list from scratch
• We can create an
empty list and then add >>> stuff = list()
elements using the >>> stuff.append('book')
append method >>> stuff.append(99)
>>> print (stuff)
• The list stays in order
['book', 99]
>>> stuff.append('cookie')
and new elements are
>>> print (stuff)
added at the end of the
['book', 99, 'cookie']
list
A List is an Ordered Sequence
list=["a","b","c","d","c"]
list.index("c",3)
Lists Operators
+ : Concatenation
* : Repetition
in : Membership
Note: - and / are not supported for lists
Concatenating lists using +
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
• We can create a new list by >>> c = a + b
adding two exsiting lists >>> print c
together [1, 2, 3, 4, 5, 6]
>>> print a
[1, 2, 3]
Repetition using *
>>> a = [1, 2, 3]
>>> n = 2
• We can repeate a list n times by >>> c = a * n
multiplying the list by n >>> print (c)
[1, 2, 3, 1, 2, 3]
• Allow Duplicates: Since lists are >>> print (a)
indexed, lists can have items with the [1, 2, 3]
same value
>>> a = [0]
>>> print (a*5)
[0, 0, 0, 0, 0]
Is Something in a List?
• Python provides two
operators that let you
check if an item is in a >>> some = [1, 9, 21, 10, 16]
list >>> 9 in some
True
• These are logical >>> 15 in some
operators that return False
True or False >>> 20 not in some
True
>>>
• They do not modify the
list
Built-in Functions and Lists
• There are a number of >>> nums = [3, 41, 12, 9, 74, 15]
functions built into >>> print(len(nums))
Python that take lists as 6
>>> print(max(nums))
parameters
74
>>> print(min(nums))
3
• Remember the loops we >>> print(sum(nums))
built? These are much 154
simpler. >>> print(sum(nums)/len(nums))
25.6
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
list constructer takes only one argument thus the brackets
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
>>> ['apple', 'banana', 'cherry']
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
• If you insert more items than you replace, the new items will be inserted where
you specified, and the remaining items will move accordingly:
• If you insert less items than you replace, the new items will be inserted where
you specified, and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
>>>['apple', 'watermelon']
Append Items
To add an item to the end of the list, use the append() method:
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Extend List
To append elements from another list to the current list, use the extend() method.
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
>>>['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
Remove Specified Item
The remove() method removes the specified item.
If you do not specify the index, the pop() method removes the last item.
List Comprehension offers the shortest syntax for looping through lists:
Examples:
• Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
>>>['apple', 'banana', 'mango']
def myfunc(n):
return abs(n - 50)
Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet?
List index()
The index() method returns the position at the first occurrence of the specified value.
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
>>>2
List Summary
• Concept of a collection
• Lists and definite loops
• Indexing and lookup
• Slicing lists
• List mutability
• List methods: append, remove, sort..
• Functions: len, min, max, sum