A list a ordered sequence of elements which can be characters, integers or even another list (referred to as a nested list). Lists are defined with brackets [
and ]
. You can create an empty list (or initialize a list) with an empty set of brackets or add elements to the lists.
emptylist = []
hobbies = ['running', 'baking', 'blogging']
The function len()
can be used to calculate the number of elements in a list.
len(hobbies)
3
To access a specific element in a list, use its index (similar to string indices). A list index must be an integer and list indices start at 0 (not 1).
hobbies[0]
list(hobbies[0])
['r', 'u', 'n', 'n', 'i', 'n', 'g']
The last line converts a string to a list of characters using the function list()
.
Similar to strings, there are many list operators. For example, the operators + and * also work on lists. The operator + concatenate lists and the operator * repeats a list a given number of times.
a = [5, 10, 15, 20]
b = [26, 30]
a + b
a * 3
[5, 10, 15, 20, 5, 10, 15, 20, 5, 10, 15, 20]
As shown above, a list is define with the bracket operator []
. The slice
operator (or colon) is used again similar to strings to extract multiple elements. The first element in a string starts with integer 0. If an index is negative, it returns the elements starting from the end of the list. Interestingly, the slice
operator starts at the index before the colon and up to but not including the integer after the index.
hobbies[0:2]
hobbies[:]
['running', 'baking', 'blogging']
Not specifying indices when using the slice operator will return all the elements in the list. Also, lists are mutable meaning they can be assigned values on the left side of the assignment operator:
hobbies[0] = "skiing"
If you want to delete a specific element in a list, you can use del
del a[1]
print a
[5, 15, 20]
Similar to strings, the in
(and not in
) operator works with lists. The operator will check if an element is in a given list and return a True
or False
:
'blogging' in hobbies
True
You can create an alias for a given list list which means you are creating more than one name of the same object. You can test if two lists are aliases using the relational operator is
. The problem is because lists are mutable, if you alter one aliased object, you will alter the other aliased object.
a = [5, 10, 15, 20]
b = a
print b is a
b[0] = 20
print "a:", a
print "b:", b
True a: [20, 10, 15, 20] b: [20, 10, 15, 20]
which will return a list [20, 10]. In general, it's best to avoid aliases and make copies instead.
The operator is
can be used to test if two lists are equal. The operators <, > can be used to test the alphabetical order of lists.
The in
operator can be used in conditional statements such as if
/ else
statements.
for elem in hobbies:
print elem
skiing baking blogging
To traverse through the sequence of elements in a list, you can use for
loops combined with len
and range
:
for i in range(len(a)):
a[i] = a[i] * 2
print a[i]
40 20 30 40
A for
loop over an empty list does not execute anything.
Another powerful feature of Python is list comprehension which maps one list onto another list and applying a function to each element. Here, we take each element in the list a
(temporarily assigning it the value i) and square each element in the list. This creates a new list and does not modify a
. In the second line, we can add a conditional statements of only squaring the elements if the element is not equal to 10.
a = [5, 10, 15, 20]
b = [i**2 for i in a]
c = [i**2 for i in a if i != 10]
print "a: ", a
print "b: ", b
print "c: ", c
a: [5, 10, 15, 20] b: [25, 100, 225, 400] c: [25, 225, 400]
Here, we take each element in the list a
(temporarily assigning it the value i) and multiply each element in the list by 2. This creates a new list and does not modify a
. In the second line, we can add a conditional statements.
Similar to strings, there are set of list methods in Python that are useful to manipulate lists. The syntax is the name of the list followed by a dot (or period) followed by the name of the list method.
append()
= add a single element to the end of a listinsert(position, element)
= inserts a single element into a list where the first argument is the index of where the element should be put and all the other elements get shifted oneextend()
= concatenates lists. Similar to append()
except, function can take in a list as an argument and appends all the elementssort()
= arrange the elements from low to high (or in alphabetical order) [Note: sort()
modifies the original list rather than returning a new list]remove(element)
= removes the first occurrence of a value from a list [Note: remove()
modifies the original list and does not return the element deleted]pop()
= deletes an element from the list and returns the element that was removed. If no index is provided as an argument, it deletes and returns the last element.a = [5, 10]
a.append(35)
a.insert(2, 22)
a.extend(b)
a.sort()
k = a.pop(0)
index(element)
= finds the first occurrence of a value in a list and returns the indexa.index(10)
0
join()
= concatenates a set of strings from a list (or a string with a given delimiter) into one string. But this method only works on lists of strings. There are two ways of joining elements of a list.print hobbies
hob2 = "/".join(hobbies)
print hob2
['skiing', 'baking', 'blogging'] skiing/baking/blogging
Because "/" is a string, the join()
method operates on the "/" object and joins together the strings in the list hobbies
, separating them using the "/". Using the string method split()
can reverse join()
by splitting a string into multiple elements based on a delimiter or vice versa.
s = "Boston is\n a\t beautiful\t city"
print s.split()
print " ".join(s.split())
['Boston', 'is', 'a', 'beautiful', 'city'] Boston is a beautiful city
It is important to note some of these methods modify the current list and other methods create new lists. For example the operators :, + and * create new lists, but append
, extend
and sort
will modify the current list. In addition, if you try to assign the newly modified list to the same variable
a = a.sort()
print a
None
then nothing will be returned.