In this part of the Python programming tutorial, we will cover Python lists in more detail.
Python list is a mutable container. It can contain mixed types. A list is an ordered collection of values. It represents a mathematical concept of a finite sequence. Values of a list are called items or elements of the list. A list can contain the same value multiple times. Each occurrence is considered a distinct item.
List elements can be accessed by their index. The first element has index 0, the last one has index -1.
Lists can contain elements of various data types.
If an index of a tuple is not a plain integer a
A
The
The syntax for list slicing is as follows:
The third index in a slice syntax is the step. It allows us to take every n-th value from a list.
Indexes can be negative numbers. Negative indexes refer to values from the end of the list. The last element has index -1, the last but one has index -2 etc. Indexes with lower negative numbers must come first in the syntax. This means that we write [-6, -2] instead of [-2, -6]. The latter returns an empty list.
The above mentioned syntax can be used in assignments. There must be an iterable on the right side of the assignment.
The second example is a bit more verbose.
The
The second example has additional dimensions.
If we do not want to change the original list, we can use the
We need to do additional work if we want to sort unicode strings.
List comprehensions provide a more concise way to create lists in situations where
In the second example we compare a list comprehension to a traditional for loop.
Today it is recommended to use list comprehensions instead of these functions where possible.
The
In this part of the Python tutorial, we have described Python lists.
Python list is a mutable container. It can contain mixed types. A list is an ordered collection of values. It represents a mathematical concept of a finite sequence. Values of a list are called items or elements of the list. A list can contain the same value multiple times. Each occurrence is considered a distinct item.
List elements can be accessed by their index. The first element has index 0, the last one has index -1.
#!/usr/bin/pythonThis is a simple list having 5 elements. The list is delimited by square brackests []. The elements of a list are separated by comma character. The contents of a list are printed to the console.
nums = [1, 2, 3, 4, 5]
print nums
$ ./simple.pyOutput of the example.
[1, 2, 3, 4, 5]
Lists can contain elements of various data types.
#!/usr/bin/pythonIn the example, we create an objects list. It contains numbers, a boolean value, another list, a string, a tuple, a custom object and a dictionary.
class Being:
pass
objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print objects
$ ./various_objects.pyOutput.
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3), <__main__.Being
instance at 0xb76a186c>, {}]
List initialization
Sometimes we need to initialize a list in advance to have a particular number of elements.#!/usr/bin/pythonIn this example we initialize two lists using a list comprehension and a * operator.
n1 = [0 for i in range(15)]
n2 = [0] * 15
print n1
print n2
n1[0:11] = [10] * 10
print n1
n1 = [0 for i in range(15)]These two lists are initialized to 15 zeros.
n2 = [0] * 15
n1[0:11] = [10] * 10First ten values are replaced with 10s.
$ ./initialization.pyExample output.
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0]
The list() function
Thelist()
function creates a list from an iterable object. An iterable may be either a sequence, a container that supports iteration, or an iterator object. If no parameter is specified, a new empty list is created. #!/usr/bin/pythonIn the example, we create an empty list, a list from a tuple, a string and another list.
a = []
b = list()
print a == b
print list((1, 2, 3))
print list("ZetCode")
print list(['Ruby', 'Python', 'Perl'])
a = []These are two ways to create an empty list.
b = list()
print a == bThe line prints True. This confirms, that a, b are equal.
print list((1, 2, 3))We create a list from a Python tuple.
print list("ZetCode")This line produces a list from a string.
print list(['Ruby', 'Python', 'Perl'])Finally, we create a copy of a list of strings.
$ ./list.pyExample output.
True
[1, 2, 3]
['Z', 'e', 't', 'C', 'o', 'd', 'e']
['Ruby', 'Python', 'Perl']
List operations
The following code shows some basic list operations.#!/usr/bin/pythonWe define two lists of integers. We use a few operators on these lists.
n1 = [1, 2, 3, 4, 5]
n2 = [3, 4, 5, 6, 7]
print n1 == n2
print n1 + n2
print n1 * 3
print 2 in n1
print 2 in n2
print n1 == n2The contents of the lists are compared with the == operator. The line prints False since the elements are different.
print n1 + n2The n1, n2 lists are added to form a new list. The new list has all elements of both the lists.
print n1 * 3We use the multiplication operator on the list. It repeats the elements n times. 3 times in our case.
print 2 in n1We use the
in
operator to find out, whether the value is present in the list. It returns a boolean True or False. $ ./lists.pyRunning the example.
False
[1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
True
False
Sequence functions
Sequence functions can be used on any sequence types, including lists.#!/usr/bin/pythonIn the example above, we have four functions. The
n = [1, 2, 3, 4, 5, 6, 7, 8]
print "There are %d items" % len(n)
print "Maximum is %d" % max(n)
print "Minimum is %d" % min(n)
print "The sum of values is %d" % sum(n)
len()
, max()
, min()
, and sum()
functions. print "There are %d items" % len(n)The
len()
function returns the size of the list. The number of elements of the list. print "Maximum is %d" % max(n)The
print "Minimum is %d" % min(n)
max()
and min()
functions return the maximum and the minimum of the list. print "The sum of values is %d" % sum(n)The
sum()
function calculates the sum of the numbers of the n list. $ ./functions.pyOutput.
There are 8 items
Maximum is 8
Minimum is 1
The sum of values is 36
Adding list elements
This section will show how elements are added to a Python list.#!/usr/bin/pythonWe have three methods to add new elements to a list. The
langs = list()
langs.append("Python")
langs.append("Perl")
print langs
langs.insert(0, "PHP")
langs.insert(2, "Lua")
print langs
langs.extend(("JavaScript", "ActionScript"))
print langs
append()
, the insert()
and the extend()
methods. langs = list()An empty list is created using the built-in
list()
method. langs.append("Python")The
langs.append("Perl")
append()
method adds an item at the end of the list. We append two strings. langs.insert(0, "PHP")The
langs.insert(2, "Lua")
insert()
method places an element at a specific position indicated by the index number. The "PHP" string is inserted at the first position, the "Lua" string at the third position. Note that list index numbers start from zero. langs.extend(("JavaScript", "ActionScript"))The
extend()
method adds a sequence of values to the end of a list. In our case two strings of a Python tuple are appended at the end of our list. $ ./adding.pyExample output.
['Python', 'Perl']
['PHP', 'Python', 'Lua', 'Perl']
['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'ActionScript']
IndexError, TypeError
TheIndexError
is raised when a list subscript is out of range. #!/usr/bin/pythonIn the script we have defined a list of 5 integers. These elements have indexes 0, 1, 2, 3 and 4. Using a bigger index leads to an error.
n = [1, 2, 3, 4, 5]
try:
n[0] = 10
n[6] = 60
except IndexError, e:
print e
n[6] = 60Index 6 is out of range for our list. An
IndexError
is thrown. except IndexError, e:We catch the error using the
print e
except
clause. In the body of the clause, we print the error message. $ ./indexerror.pyExample output.
list assignment index out of range
If an index of a tuple is not a plain integer a
TypeError
is thrown. #!/usr/bin/pythonThis example throws a
n = [1, 2, 3, 4, 5]
try:
print n[1]
print n['2']
except TypeError, e:
print "Error in file %s" % __file__
print "Message: %s" % e
TypeError
. print n['2']A list index must be an integer. Other types end in error.
except TypeError, e:In the except block, we print the name of the file, where the exception has occured and the message string.
print "Error in file %s" % __file__
print "Message: %s" % e
$ ./typeerror.pyOutput of the script.
2
Error in file ./typeerror.py
Message: list indices must be integers, not str
Removing elements
Previously we have added items to a list. Now we will be removing them from a list.#!/usr/bin/pythonThe
langs = ["Python", "Ruby", "Perl", "Lua", "JavaScript"]
print langs
langs.pop(3)
langs.pop()
print langs
langs.remove("Ruby")
print langs
pop()
method removes and returns an element with a specified index or the last element, if the index number is not given. The remove()
method removes a particular item from a Python list. langs.pop(3)We take away the element which has index 3. The second line removes and returns the last element from the list, namely "JavaScript" string.
langs.pop()
langs.remove("Ruby")This line removes a "Ruby" string from the langs list.
$ ./removing.pyFrom the ouput of the script we can see the effects of the described methods.
['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
['Python', 'Ruby', 'Perl']
['Python', 'Perl']
A
del
keyword can be used to delete list elements as well. #!/usr/bin/pythonWe have a list of strings. We use the
langs = ["Python", "Ruby", "Perl", "Lua", "JavaScript"]
print langs
del langs[1]
print langs
#del langs[15]
del langs[:]
print langs
del
keyword to delete list elements. del langs[1]We remove the second string from the list. It is the "Ruby" string.
#del langs[15]We can delete only existing elements. If we uncomment the code line, we will receive an
IndexError
message. del langs[:]Here we remove all the remaining elements from the list. The [:] characters refer to all items of a list.
$ ./removing2.pyRunning the script.
['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
['Python', 'Perl', 'Lua', 'JavaScript']
[]
Modifying elements
In the next example we will be modifying list elements.#!/usr/bin/pythonIn the example we modify the third element of the langs list twice.
langs = ["Python", "Ruby", "Perl"]
langs.pop(2)
langs.insert(2, "PHP")
print langs
langs[2] = "Perl"
print langs
langs.pop(2)One way to modify an element is to remove it and place a different element at the same position.
langs.insert(2, "PHP")
langs[2] = "Perl"The other method is more straightforward. We assign a new element at a given position. Now there is "Perl" string at the third position again.
$ ./modify.pyOutput.
['Python', 'Ruby', 'PHP']
['Python', 'Ruby', 'Perl']
Copying lists
There are several ways how we can copy a list in Python. We will mention a few of them.#!/usr/bin/pythonWe have a list of three strings. We make a copy of the list seven times.
import copy
w = ["Python", "Ruby", "Perl"]
c1 = w[:]
c2 = list(w)
c3 = copy.copy(w)
c4 = copy.deepcopy(w)
c5 = [e for e in w]
c6 = []
for e in w:
c6.append(e)
c7 = []
c7.extend(w)
print c1, c2, c3, c4, c5, c6, c7
import copyWe import the
copy
module, which has two methods for copying. c1 = w[:]A list is copied using the slice syntax.
c2 = list(w)The
list()
function creates a copy of a list, when it takes a list as a parameter. c3 = copy.copy(w)The
c4 = copy.deepcopy(w)
copy()
method produces a shallow copy of a list. The deepcopy
produces a deep copy of a list. c5 = [e for e in w]A copy of a string is created using list comprehension.
c6 = []A copy created by a for loop.
for e in w:
c6.append(e)
c7 = []The
c7.extend(w)
extend
method can be used to create a copy too. $ ./copying.pySeven copies of a string list were created.
['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl']
['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl']
['Python', 'Ruby', 'Perl']
Indexing list elements
Elements in a Python list can be accessed by their index. Index numbers are integers; they start from zero. Indexes can be negative; they refer to elements from the end of the list. The first item in a list has index 0, the last item has -1.#!/usr/bin/pythonWe can access an element of a list by its index. The index is placed between the square brackets [] after the name of the list.
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[0]
print n[-1]
print n[-2]
print n[3]
print n[5]
print n[0]These three lines print the first, the last and the last but one item of the list.
print n[-1]
print n[-2]
print n[3]The two lines print the fourth and sixth element of the list.
print n[5]
$ ./indexing.pyExample output.
1
8
7
4
6
The
index(e, start, end)
method looks for a particular element and returns its lowest index. The start and end are optional parameters, that limit the search to given boundaries. #!/usr/bin/pythonA code example with the
n = [1, 2, 3, 4, 1, 2, 3, 1, 2]
print n.index(1)
print n.index(2)
print n.index(1, 1)
print n.index(2, 2)
print n.index(1, 2, 5)
print n.index(3, 4, 8)
index()
method. print n.index(1)These two lines print the indexes of the leftmost 1, 2 values of the n list.
print n.index(2)
print n.index(1, 1)Here we search for 1, 2, numbers after specified indexes.
print n.index(2, 2)
print n.index(1, 2, 5)Finally, we search for value 1 between values with indexes 2-5.
$ ./indexing2.pyExample output.
0
1
4
5
4
6
Slicing
List slicing is an operation that extracts certain elements from a list and forms them into another list. Possibly with different number of indices and different index ranges.The syntax for list slicing is as follows:
[start:end:step]The start, end, step parts of the syntax are integers. Each of them is optional. They can be both positive and negative. The value having the end index is not included in the slice.
#!/usr/bin/pythonWe create four slices from a list of 8 integers.
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[1:5]
print n[:5]
print n[1:]
print n[:]
print n[1:5]The first slice has values with indexes 1, 2, 3 and 4. The newly formed list is [2, 3, 4, 5].
print n[:5]If the start index is omitted then a default value is assumed, which is 0. The slice is [1, 2, 3, 4, 5].
print n[1:]If the end index is omitted, the -1 default value is taken. In such a case a slice takes all values to the end of the list.
print n[:]Even both indexes can be left out. This syntax creates a copy of a list.
$ ./slice.pyOutput of the example.
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
The third index in a slice syntax is the step. It allows us to take every n-th value from a list.
#!/usr/bin/pythonWe form four new lists using the step value.
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[1:9:2]
print n[::2]
print n[::1]
print n[1::3]
print n[1:9:2]Here we create a slice having every second element from the n list, starting from the second element, ending in the eighth element. The new list has [2, 4, 6, 8] elements.
print n[::2]Here we build a slice by taking every second value from the beginning to the end of the list.
print n[::1]This creates a copy of a list.
print n[1::3]The slice has every third element from the second element to the end of the n list.
$ ./slice2.pyOutput of the example.
[2, 4, 6, 8]
[1, 3, 5, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 5, 8]
Indexes can be negative numbers. Negative indexes refer to values from the end of the list. The last element has index -1, the last but one has index -2 etc. Indexes with lower negative numbers must come first in the syntax. This means that we write [-6, -2] instead of [-2, -6]. The latter returns an empty list.
#!/usr/bin/pythonIn this script, we form five lists. We also use negative index numbers.
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[-4:-1]
print n[-1:-4]
print n[-5:]
print n[-6:-2:2]
print n[::-1]
print n[-4:-1]The first line returns [5, 6, 7], the second line returns an empty list. Lower indexes must come before higher indexes.
print n[-1:-4]
print n[::-1]This creates a reversed list.
$ ./slice3.pyOutput of the example.
[5, 6, 7]
[]
[4, 5, 6, 7, 8]
[3, 5]
[8, 7, 6, 5, 4, 3, 2, 1]
The above mentioned syntax can be used in assignments. There must be an iterable on the right side of the assignment.
#!/usr/bin/pythonWe have a list of 8 integers. We use the slice syntax to replace the elements with new values.
n = [1, 2, 3, 4, 5, 6, 7, 8]
n[0] = 10
n[1:3] = 20, 30
n[3::1] = 40, 50, 60, 70, 80
print n
Traversing lists
This section will point out three basic ways to traverse a list in Python.#!/usr/bin/pythonThe first one is the most straightforward way to traverse a list.
n = [1, 2, 3, 4, 5]
for e in n:
print e,
n = [1, 2, 3, 4, 5]We have a numberical list. There are five integers in the list.
for e in n:Using the
print e,
for
loop, we go through the list one by one and print the current element to the console. $ ./traverse.pyThis is the output of the script. The integers are printed to the terminal.
1 2 3 4 5
The second example is a bit more verbose.
#!/usr/bin/pythonWe are traversing the list using the
n = [1, 2, 3, 4, 5]
i = 0
s = len(n)
while i < s:
print n[i],
i = i + 1
while
loop. i = 0First we need to define a counter and find out the size of the list.
l = len(n)
while i < s:With the help of these two numbers, we go through the list and print each element to the terminal.
print n[i],
i = i + 1
The
enumerate()
built-in function gives us both the index and the value of a list in a loop. #!/usr/bin/pythonIn the example, we print the values and the indexes of the values.
n = [1, 2, 3, 4, 5]
for e, i in enumerate(n):
print "n[%d] = %d" % (e, i)
$ ./traverse3.pyRunning the script.
n[0] = 1
n[1] = 2
n[2] = 3
n[3] = 4
n[4] = 5
Counting list elements
Sometimes it is important to count list elements. How many times they are present in the Python list. Thecount()
method is suited for this. #!/usr/bin/pythonIn this example, we count the number of occurences of a few numbers in the n list.
n = [1, 1, 2, 3, 4, 4, 4, 5]
print n.count(4)
print n.count(1)
print n.count(2)
print n.count(6)
n = [1, 1, 2, 3, 4, 4, 4, 5]We have a list of integer numbers. 1, 4 integers are present multiple times.
print n.count(4)Using the
print n.count(1)
print n.count(2)
print n.count(6)
count()
method, we find out the occurence of 4, 1, 2, 6 numbers. $ ./counting.pyScript output. Number 4 is present 3 times, 1 twice, 2 once and 6 is not present in the list.
3
2
1
0
Nested lists
It is possible to nest lists into another lists. With a nested list a new dimension is created. To access nested lists one needs additional square brackets [].#!/usr/bin/pythonIn the example, we have three nested lists having two elements each.
nums = [[1, 2], [3, 4], [5, 6]]
print nums[0]
print nums[1]
print nums[2]
print nums[0][0]
print nums[0][1]
print nums[1][0]
print nums[2][1]
print len(nums)
print nums[0]Three nested lists of the nums list are printed to the console.
print nums[1]
print nums[2]
print nums[0][0]Here we print the two elements of the first nested list. The nums[0] refers to the first nested list; the nums[0][0] refers to the first element of the first nested list, namely 1.
print nums[0][1]
print len(nums)The line prints 3. Each nested list is counted as one element. Its inner elements are not taken into account.
$ ./multi.pyExample output.
[1, 2]
[3, 4]
[5, 6]
1
2
3
6
3
The second example has additional dimensions.
#!/usr/bin/pythonIn the example, the [5, 6] list is nested into [3, 4, ...] list, the [3, 4, [4, 6]] is nested into the [1, 2, ...] list which is finally an element of the nums list.
nums = [[1, 2, [3, 4, [5, 6]]]]
print nums[0]
print nums[0][2]
print nums[0][2][2]
print nums[0][0]
print nums[0][2][1]
print nums[0][2][2][0]
print nums[0]These three lines print the nested lists to the console.
print nums[0][2]
print nums[0][2][2]
print nums[0][0]Here three elements are accessed. Additional brackets [] are needed when referring to inner lists.
print nums[0][2][1]
print nums[0][2][2][0]
$ ./multi2.pyExample output.
[1, 2, [3, 4, [5, 6]]]
[3, 4, [5, 6]]
[5, 6]
1
4
5
Sorting lists
In this section we will sort list elements. Python has a built-in list methodsort()
and sorted()
function for doing sorting. #!/usr/bin/pythonIn the code example, we have a list of unsorted integers. We sort the elements using the
n = [3, 4, 7, 1, 2, 8, 9, 5, 6]
print n
n.sort()
print n
n.sort(reverse=True)
print n
sort()
method. The method sorts the elements in-place; the original list is modified. n.sort()The
sort()
method sorts the elements in ascending order. n.sort(reverse=True)With the reverse parameter set to True, the list is sorted in a descending order.
$ ./sort.pyIn the ouput we can see the original list, the sorted list in ascending and descending orders.
[3, 4, 7, 1, 2, 8, 9, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
If we do not want to change the original list, we can use the
sorted
function. This function creates a new sorted list. #!/usr/bin/pythonIn the example, we use the
n = [3, 4, 1, 7, 2, 5, 8, 6]
print n
print sorted(n)
print n
sorted()
function to sort the elements of a list. $ ./sort2.pyFrom the ouput of the script we can see, that the original list is not modified.
[3, 4, 1, 7, 2, 5, 8, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
[3, 4, 1, 7, 2, 5, 8, 6]
We need to do additional work if we want to sort unicode strings.
#!/usr/bin/pythonWe have a list of six unicode strings. We change the locale settings to sort the strings according to current language option.
# -*- coding: utf-8 -*-
import locale
from functools import cmp_to_key
w = [u'zem', u'štebot', u'rum', u'železo', u'prameň', u"sob"]
locale.setlocale(locale.LC_COLLATE, ('sk_SK', 'UTF8'))
w.sort(key=cmp_to_key(locale.strcoll))
for e in w:
print e
import localeWe import the
from functools import cmp_to_key
locale
module and the cmp_to_key
conversion function. w = [u'zem', u'štebot', u'rum', u'železo', u'prameň', u"sob"]This is a list of six strings. The strings are in Slovak language and have some diacritical marks. They play role in sorting the characters correctly.
locale.setlocale(locale.LC_COLLATE, ('sk_SK', 'UTF8'))We set the locale lettings for the Slovak language.
w.sort(key=cmp_to_key(locale.strcoll))We sort the list. The locale.strcoll compares two strings according to the current LC_COLLATE setting. The cmp_to_key function transform an old-style comparison function to a key-function.
for e in w:We print the sorted words to the console.
print e
$ ./sort_locale.pyThe elements were correctly sorted. The specifics of the Slovak alphabet were taken into account.
prameň
rum
sob
štebot
zem
železo
Reversing elements
We can reverse elements in a list in a few ways in Python. Reversing elements should not be confused with sorting in a reverse way.#!/usr/bin/pythonIn the example, we have three identical string lists. We reverse the elements in three ways.
a1 = ["bear", "lion", "tiger", "eagle"]
a2 = ["bear", "lion", "tiger", "eagle"]
a3 = ["bear", "lion", "tiger", "eagle"]
a1.reverse()
print a1
it = reversed(a2)
r = list()
for e in it:
r.append(e)
print r
print a3[::-1]
a1.reverse()The first way is to use the
reverse()
method. it = reversed(a2)The
r = list()
for e in it:
r.append(e)
print r
reversed()
function returns a reverse iterator. We use the iterator in a for loop and create a new reversed list. print a3[::-1]The third way is to reverse the list using the slice syntax, where the step parameter is set to -1.
$ ./reverse.pyAll the three lists were reversed OK.
['eagle', 'tiger', 'lion', 'bear']
['eagle', 'tiger', 'lion', 'bear']
['eagle', 'tiger', 'lion', 'bear']
List comprehensions
A list comprehension is a syntactic construct which creates a list based on existing list. The syntax was influenced by mathematical notation of sets. The Python syntax was inspired by the Haskell programming language.L = [expression for variable in sequence [if condition]]The above pseudo code shows the syntax of a list comprehension. A list comprehension creates a new list. It is based on an existing list. A for loop goes through the sequence. For each loop an expression is evaluated if the condition is met. If the value is computed it is appended to the new list.
List comprehensions provide a more concise way to create lists in situations where
map()
and filter()
and/or nested loops could be used. #!/usr/bin/pythonIn the example we have defined a list of numbers. With the help of the list comprehension, we create a new list of numbers that cannot be divided by 2 without a remainder.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [e for e in a if e % 2]
print b
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]This is the list of 9 integers.
b = [e for e in a if e % 2]Here we have the list comprehension. In the
for e in a
loop each element of a list is taken. Then a if e % 2
condition is tested. If the condition is met, an expression is evaluated. In our case the expression is a pure e
which takes the element as it is. Finally the element is appended to the list. $ ./list_comprehension.pyExample output. The numbers in a list cannot be divided by 2, without a remainder.
[1, 3, 5, 7, 9]
In the second example we compare a list comprehension to a traditional for loop.
#!/usr/bin/pythonIn the example we have a string. We want to create a list of the ASCII integer codes of the letters of the string.
lang = "Python"
a = []
for e in lang:
a.append(ord(e))
b = [ord(e) for e in lang]
print a
print b
a = []We create such a list with the for loop.
for e in lang:
a.append(ord(e))
b = [ord(e) for e in lang]Here the same is produced using a list comprehension. Note that the if condition was omitted. It is optional.
$ ./list_comprehension2.pyExample output.
[80, 121, 116, 104, 111, 110]
[80, 121, 116, 104, 111, 110]
The map() and filter() functions
Themap()
and filter()
functions are mass functions that work on all list items. They are part of the functional programming built into the Python language. Today it is recommended to use list comprehensions instead of these functions where possible.
#!/usr/bin/pythonThe
def to_upper(s):
return s.upper()
words = ["stone", "cloud", "dream", "sky"]
words2 = map(to_upper, words)
print words2
map()
function applies a particular function to every element of a list. def to_upper(s):This is the definition of the function, that will be applied to every list element. It calls the
return s.upper()
upper()
string method on a given string. words = ["stone", "cloud", "dream", "sky"]This is the list of strings.
words2 = map(to_upper, words)The
print words2
map()
function applies the to_upper()
function to every string element of the words list. A new list is formed and returned back. We print it to the console. $ ./map.pyEvery item of the list is in capital letters.
['STONE', 'CLOUD', 'DREAM', 'SKY']
The
filter()
function constructs a list from those elements of the list for which a function returns true. #!/usr/bin/pythonAn example demonstrating the
def positive(x):
return x > 0
n = [-2, 0, 1, 2, -3, 4, 4, -1]
print filter(positive, n)
filter()
function. It will create a new list having only positive values. It will filter out all negative values and 0. def positive(x):This is the definition of the function used by the
return x > 0
filter()
function. It returns True or False. Functions that return a boolean value are called predicates. $ ./filter.pyOutput of the filter.py script.
[1, 2, 4, 4]
In this part of the Python tutorial, we have described Python lists.
0 comments:
Post a Comment