Programming - 11

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Programming - 11

3-quarter

week-1 (33-34)

Lists and String Methods


11.2.2.3 apply functions and string processing methods;
Learning objectives 11.2.3.3 apply functions and methods of processing lists;
11.4.3.2 solve applied problems of various subject areas.

The list data type has some more methods. Here are all of the methods of
list objects:

list.append(x) Add an item to the end of the list. Equivalent


to a[len(a):] = [x] .

list.extend(iterable) Extend the list by appending all the items from the
iterable. Equivalent to a[len(a):] = iterable .

list.insert(i, x) Insert an item at a given position. The first argument is


the index of the element before which to insert, so a.insert(0, x) inserts
at the front of the list, and a.insert(len(a), x) is equivalent
to a.append(x) .

list.remove(x) Remove the first item from the list whose value is equal
to x. It raises a ValueError if there is no such item.

list.pop([i]) Remove the item at the given position in the list, and return
it. If no index is specified, a.pop() removes and returns the last item in
the list. (The square brackets around the i in the method signature
denote that the parameter is optional, not that you should type square
brackets at that position. You will see this notation frequently in the
Python Library Reference.)

list.clear() Remove all items from the list. Equivalent to del a[:] .

list.index(x[, start[, end]]) Return zero-based index in the list of the first
item whose value is equal to x. Raises a ValueError if there is no such
item.
The optional arguments start and end are interpreted as in the slice

Programming - 11 1
notation and are used to limit the search to a particular subsequence of
the list. The returned index is computed relative to the beginning of the
full sequence rather than the start argument.

list.count(x) Return the number of times x appears in the list.

list.sort(*, key=None, reverse=False) Sort the items of the list in place


(the arguments can be used for sort customization, see sorted() for
their explanation).

list.reverse() Reverse the elements of the list in place.

list.copy() Return a shallow copy of the list. Equivalent to a[:] .

An example that uses most of the list methods:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']


>>>fruits.count('apple')
2
>>>fruits.count('tangerine')
0
>>>fruits.index('banana')
3
>>>fruits.index('banana', 4)# Find next banana starting at position 46
>>>fruits.reverse()
>>>fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>>fruits.append('grape')
>>>fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>>fruits.sort()
>>>fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>>fruits.pop()
'pear'

You might have noticed that methods like insert , remove or sort that only
modify the list have no return value printed – they return the
default None . This is a design principle for all mutable data structures in
Python.

Another thing you might notice is that not all data can be sorted or
compared. For instance, [None, 'hello', 10] doesn’t sort because integers
can’t be compared to strings and None can’t be compared to other types.

Programming - 11 2
📖 Extra Reading:
An Overview of Python List Methods
List methods in Python
Python List Methods

Using Lists as Stacks


The list methods make it very easy to use a list as a stack, where the last
element added is the first element retrieved (“last-in, first-out”). To add an
item to the top of the stack, use append() . To retrieve an item from the top of
the stack, use pop() without an explicit index. For example:

>>> stack = [3, 4, 5]


>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

📖 Extra Reading:
Stack Data Structure
Everything You Need to Know About Stacks in Python
How to Implement a Python Stack
Stack in Python: How To Implement Python Stack?
Stack Data Structure (video)

Using Lists as Queues


It is also possible to use a list as a queue, where the first element added is
the first element retrieved (“first-in, first-out”); however, lists are not efficient
for this purpose. While appends and pops from the end of list are fast, doing

Programming - 11 3
inserts or pops from the beginning of a list is slow (because all of the other
elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have


fast appends and pops from both ends. For example:

>>> from collections import deque


>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

📖 Extra Reading:
Stack Data Structure
Everything You Need to Know About Stacks in Python
How to Implement a Python Stack
Stack in Python: How To Implement Python Stack?
Queue Data Structure (video)

week-2 (35-36)

List and String Methods


11.2.2.3 apply functions and string processing methods; 11.2.3.3
Learning
apply functions and methods of processing lists; 11.4.3.2 solve
objectives
applied problems of various subject areas.

Strings implement all of the common sequence operations, along with the
additional methods described below.
Strings also support two styles of string formatting, one providing a large
degree of flexibility and customization (see str.format() , Format String
Syntax and Custom String Formatting) and the other based on
C printf style formatting that handles a narrower range of types and is
slightly harder to use correctly, but is often faster for the cases it can handle
(printf-style String Formatting).

Programming - 11 4
The Text Processing Services section of the standard library covers a
number of other modules that provide various text related utilities (including
regular expression support in the re module).

str.capitalize() Return a copy of the string with its first character


capitalized and the rest lowercased.
Changed in version 3.8: The first character is now put into titlecase
rather than uppercase. This means that characters like digraphs will only
have their first letter capitalized, instead of the full character.

str.casefold() Return a casefolded copy of the string. Casefolded strings


may be used for caseless matching.
Casefolding is similar to lowercasing but more aggressive because it is
intended to remove all case distinctions in a string. For example, the
German lowercase letter 'ß' is equivalent to "ss" . Since it is already
lowercase, lower() would do nothing to 'ß' ; casefold() converts it
to "ss" .
The casefolding algorithm is described in section 3.13 of the Unicode
Standard.
New in version 3.3.

str.center (width[, fillchar])Return centered in a string of length width.


Padding is done using the specified fillchar (default is an ASCII space).
The original string is returned if width is less than or equal to len(s) .

str.count (sub[, start[, end]]) Return the number of non-overlapping


occurrences of substring sub in the range [start, end]. Optional
arguments start and end are interpreted as in slice notation.
If sub is empty, returns the number of empty strings between characters
which is the length of the string plus one.

str.encode (encoding='utf-8', errors='strict') Return the string encoded


to bytes .
encoding defaults to 'utf-8' ; see Standard Encodings for possible
values.
errors controls how encoding errors are handled. If 'strict' (the
default), a UnicodeError exception is raised. Other possible values
are 'ignore' , 'replace' , 'xmlcharrefreplace' , 'backslashreplace' and any
other name registered via codecs.register_error() . See Error
Handlers for details.
For performance reasons, the value of errors is not checked for validity

Programming - 11 5
unless an encoding error actually occurs, Python Development Mode is
enabled or a debug build is used.
Changed in version 3.1: Added support for keyword arguments.
Changed in version 3.9: The value of the errors argument is now
checked in Python Development Mode and in debug mode.

str.endswith(suffix[, start[, end]]) Return True if the string ends with the
specified suffix, otherwise return False . suffix can also be a tuple of
suffixes to look for. With optional start, test beginning at that position.
With optional end, stop comparing at that position.

str.expandtabs(tabsize=8) Return a copy of the string where all tab


characters are replaced by one or more spaces, depending on the
current column and the given tab size. Tab positions occur
every tabsize characters (default is 8, giving tab positions at columns 0,
8, 16 and so on). To expand the string, the current column is set to zero
and the string is examined character by character. If the character is a
tab ( \t ), one or more space characters are inserted in the result until
the current column is equal to the next tab position. (The tab character
itself is not copied.) If the character is a newline ( \n ) or return ( \r ), it is
copied and the current column is reset to zero. Any other character is
copied unchanged and the current column is incremented by one
regardless of how the character is represented when printed.

>>> '01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234'

str.find(sub[, start[, end]]) Return the lowest index in the string where
substring sub is found within the slice s[start:end] . Optional
arguments start and end are interpreted as in slice notation.
Return -1 if sub is not found.
Note
The find() method should be used only if you need to know the position
of sub. To check if sub is a substring or not, use the in operator:

>>> 'Py' in 'Python'


True

Programming - 11 6
str.format(*args, **kwargs)Perform a string formatting operation. The
string on which this method is called can contain literal text or
replacement fields delimited by braces {} . Each replacement field
contains either the numeric index of a positional argument, or the name
of a keyword argument. Returns a copy of the string where each
replacement field is replaced with the string value of the corresponding
argument.

>>> "The sum of 1 + 2 is {0}".format(1+2)


'The sum of 1 + 2 is 3'

See Format String Syntax for a description of the various formatting


options that can be specified in format strings.

str.index(sub[, start[, end]]) Like find() , but raise ValueError when the
substring is not found.

str.isalnum() Return True if all characters in the string are alphanumeric


and there is at least one character, False otherwise. A character c is
alphanumeric if one of the following
returns True : c.isalpha() , c.isdecimal() , c.isdigit() , or c.isnumeric() .

str.isalpha() Return True if all characters in the string are alphabetic


and there is at least one character, False otherwise. Alphabetic
characters are those characters defined in the Unicode character
database as “Letter”, i.e., those with general category property being
one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the
“Alphabetic” property defined in the Unicode Standard.

str.isascii() Return True if the string is empty or all characters in the


string are ASCII, False otherwise. ASCII characters have code points in
the range U+0000-U+007F.
New in version 3.7.

str.isdecimal() Return True if all characters in the string are decimal


characters and there is at least one character, False otherwise. Decimal
characters are those that can be used to form numbers in base 10, e.g.
U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a
character in the Unicode General Category “Nd”.

str.isdigit() Return True if all characters in the string are digits and there
is at least one character, False otherwise. Digits include decimal

Programming - 11 7
characters and digits that need special handling, such as the
compatibility superscript digits. This covers digits which cannot be used
to form numbers in base 10, like the Kharosthi numbers. Formally, a digit
is a character that has the property value Numeric_Type=Digit or
Numeric_Type=Decimal.

str.islower()Return True if all cased characters 4 in the string are


lowercase and there is at least one cased character, False otherwise.

str.isnumeric()Return True if all characters in the string are numeric


characters, and there is at least one character, False otherwise.
Numeric characters include digit characters, and all characters that have
the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION
ONE FIFTH. Formally, numeric characters are those with the property
value Numeric_Type=Digit, Numeric_Type=Decimal or
Numeric_Type=Numeric.

str.isprintable()Return True if all characters in the string are printable or


the string is empty, False otherwise. Nonprintable characters are those
characters defined in the Unicode character database as “Other” or
“Separator”, excepting the ASCII space (0x20) which is considered
printable. (Note that printable characters in this context are those which
should not be escaped when repr() is invoked on a string. It has no
bearing on the handling of strings written to sys.stdout or sys.stderr .)

str.isspace()Return True if there are only whitespace characters in the


string and there is at least one character, False otherwise.
A character is whitespace if in the Unicode character database
(see unicodedata ), either its general category is Zs (“Separator, space”),
or its bidirectional class is one of WS , B , or S .

str.istitle()Return True if the string is a titlecased string and there is at


least one character, for example uppercase characters may only follow
uncased characters and lowercase characters only cased ones.
Return False otherwise.

str.isupper()Return True if all cased characters 4 in the string are


uppercase and there is at least one cased character, False otherwise.=

>>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False

Programming - 11 8
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False

str.join(iterable)Return a string which is the concatenation of the strings


in iterable. A TypeError will be raised if there are any non-string values
in iterable, including bytes objects. The separator between elements is
the string providing this method.

str.ljust(width[, fillchar])Return the string left justified in a string of


length width. Padding is done using the specified fillchar (default is an
ASCII space). The original string is returned if width is less than or equal
to len(s) .

str.lower()Return a copy of the string with all the cased


characters 4 converted to lowercase.
The lowercasing algorithm used is described in section 3.13 of the
Unicode Standard.

str.lstrip([chars])Return a copy of the string with leading characters


removed. The chars argument is a string specifying the set of characters
to be removed. If omitted or None , the chars argument defaults to
removing whitespace. The chars argument is not a prefix; rather, all
combinations of its values are stripped:

>>> ' spacious '.lstrip()


'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

See str.removeprefix() for a method that will remove a single prefix


string rather than all of a set of characters. For example:

>>> 'Arthur: three!'.lstrip('Arthur: ')


'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!'

str.partition(sep)Split the string at the first occurrence of sep, and return


a 3-tuple containing the part before the separator, the separator itself,

Programming - 11 9
and the part after the separator. If the separator is not found, return a 3-
tuple containing the string itself, followed by two empty strings.

str.removeprefix(prefix, /)If the string starts with the prefix string,


return string[len(prefix):] . Otherwise, return a copy of the original
string:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

New in version 3.9.

str.removesuffix(suffix, /)If the string ends with the suffix string and
that suffix is not empty, return string[:-len(suffix)] . Otherwise, return a
copy of the original string:

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'

New in version 3.9.

str.replace(old, new[, count])Return a copy of the string with all


occurrences of substring old replaced by new. If the optional
argument count is given, only the first count occurrences are replaced.

str.rfind(sub[, start[, end]])Return the highest index in the string where


substring sub is found, such that sub is contained within s[start:end] .
Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.

str.rindex(sub[, start[, end]])Like rfind() but raises ValueError when the


substring sub is not found.

str.rjust(width[, fillchar])Return the string right justified in a string of


length width. Padding is done using the specified fillchar (default is an
ASCII space). The original string is returned if width is less than or equal
to len(s) .

str.rpartition(sep)Split the string at the last occurrence of sep, and


return a 3-tuple containing the part before the separator, the separator

Programming - 11 10
itself, and the part after the separator. If the separator is not found,
return a 3-tuple containing two empty strings, followed by the string
itself.

str.rsplit(sep=None, maxsplit=- 1)Return a list of the words in the string,


using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done, the rightmost ones. If sep is not specified
or None , any whitespace string is a separator. Except for splitting from
the right, rsplit() behaves like split() which is described in detail
below.

str.rstrip([chars])Return a copy of the string with trailing characters


removed. The chars argument is a string specifying the set of characters
to be removed. If omitted or None , the chars argument defaults to
removing whitespace. The chars argument is not a suffix; rather, all
combinations of its values are stripped:

>>> ' spacious '.rstrip()


' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'

See str.removesuffix() for a method that will remove a single suffix


string rather than all of a set of characters. For example:

>>> 'Monty Python'.rstrip(' Python')


'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty'

str.split(sep=None, maxsplit=- 1)Return a list of the words in the string,


using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done (thus, the list will have at
most maxsplit+1 elements). If maxsplit is not specified or -1 , then there
is no limit on the number of splits (all possible splits are made).
If sep is given, consecutive delimiters are not grouped together and are
deemed to delimit empty strings (for
example, '1,,2'.split(',') returns ['1', '', '2'] ). The sep argument
may consist of multiple characters (for
example, '1<>2<>3'.split('<>') returns ['1', '2', '3'] ). Splitting an

Programming - 11 11
empty string with a specified separator returns [''] .
For example:

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']

If sep is not specified or is None , a different splitting algorithm is applied:


runs of consecutive whitespace are regarded as a single separator, and
the result will contain no empty strings at the start or end if the string has
leading or trailing whitespace. Consequently, splitting an empty string or
a string consisting of just whitespace with a None separator returns [] .
For example:

>>> '1 2 3'.split()


['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> ' 1 2 3 '.split()
['1', '2', '3']

str.startswith(prefix[, start[, end]])Return True if string starts with


the prefix, otherwise return False . prefix can also be a tuple of prefixes
to look for. With optional start, test string beginning at that position. With
optional end, stop comparing string at that position.

str.strip([chars])Return a copy of the string with the leading and trailing


characters removed. The chars argument is a string specifying the set of
characters to be removed. If omitted or None , the chars argument
defaults to removing whitespace. The chars argument is not a prefix or
suffix; rather, all combinations of its values are stripped:

>>> ' spacious '.strip()


'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'

The outermost leading and trailing chars argument values are stripped
from the string. Characters are removed from the leading end until

Programming - 11 12
reaching a string character that is not contained in the set of characters
in chars. A similar action takes place on the trailing end. For example:

>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'


>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'

str.swapcase()Return a copy of the string with uppercase characters


converted to lowercase and vice versa. Note that it is not necessarily
true that s.swapcase().swapcase() == s .

str.title()Return a titlecased version of the string where words start with


an uppercase character and the remaining characters are lowercase.
For example:

>>> 'Hello world'.title()


'Hello World'

The algorithm uses a simple language-independent definition of a word


as groups of consecutive letters. The definition works in many contexts
but it means that apostrophes in contractions and possessives form
word boundaries, which may not be the desired result:

>>> "they're bill's friends from the UK".title()


"They'Re Bill'S Friends From The Uk"

The string.capwords() function does not have this problem, as it splits


words on spaces only.

>>> import re>>> def titlecase(s):


... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0).capitalize(),
... s)
...>>> titlecase("they're bill's friends.")
"They're Bill's Friends."

str.upper()Return a copy of the string with all the cased


characters 4 converted to uppercase. Note
that s.upper().isupper() might be False if s contains uncased
characters or if the Unicode category of the resulting character(s) is not

Programming - 11 13
“Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).
The uppercasing algorithm used is described in section 3.13 of the
Unicode Standard.

str.zfill(width)Return a copy of the string left filled with ASCII '0' digits
to make a string of length width. A leading sign prefix ( '+' / '-' ) is
handled by inserting the padding after the sign character rather than
before. The original string is returned if width is less than or equal
to len(s) .
For example:

>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'

printf style String Formatting

Note: The formatting operations described here exhibit a


variety of quirks that lead to a number of common errors
(such as failing to display tuples and dictionaries
correctly). Using the newer formatted string literals,
the str.format() interface, or template strings may help
avoid these errors. Each of these alternatives provides
their own trade-offs and benefits of simplicity, flexibility,
and/or extensibility.

String objects have one unique built-in operation: the % operator (modulo).
This is also known as the string formatting or interpolation operator.
Given format % values (where format is a string), % conversion specifications
in format are replaced with zero or more elements of values. The effect is
similar to using the sprintf() in the C language.
If format requires a single argument, values may be a single non-tuple
object. 5 Otherwise, values must be a tuple with exactly the number of items
specified by the format string, or a single mapping object (for example, a
dictionary).

Programming - 11 14
A conversion specifier contains two or more characters and has the following
components, which must occur in this order:

1. The '%' character, which marks the start of the specifier.

2. Mapping key (optional), consisting of a parenthesised sequence of


characters (for example, (somename) ).

3. Conversion flags (optional), which affect the result of some conversion


types.

4. Minimum field width (optional). If specified as an '*' (asterisk), the


actual width is read from the next element of the tuple in values, and the
object to convert comes after the minimum field width and optional
precision.

5. Precision (optional), given as a '.' (dot) followed by the precision. If


specified as '*' (an asterisk), the actual precision is read from the next
element of the tuple in values, and the value to convert comes after the
precision.

6. Length modifier (optional).

7. Conversion type.

When the right argument is a dictionary (or other mapping type), then the
formats in the string must include a parenthesised mapping key into that
dictionary inserted immediately after the '%' character. The mapping key
selects the value to be formatted from the mapping. For example:

>>> print('%(language)s has %(number)03d quote types.' %


... {'language': "Python", "number": 2})
Python has 002 quote types.

In this case no * specifiers may occur in a format (since they require a


sequential parameter list).
The conversion flag characters are:

Flag Meaning

The value conversion will use the “alternate form” (where defined
'#'
below).
'0' The conversion will be zero padded for numeric values.
'-'
The converted value is left adjusted (overrides

Programming - 11 15
the '0' conversion if both are given).

(a space) A blank should be left before a positive number (or


'
empty string) produced by a signed conversion.

A sign character ( '+' or '-' ) will precede the conversion


'+'
(overrides a “space” flag).

A length modifier ( h , l , or L ) may be present, but is ignored as it is not


necessary for Python – so e.g. %ld is identical to %d .

week-3-4 (37-40)

Nested Lists
11.2.3.4 create nested lists; 11.2.3.5 enter elements of nested
Learning
lists from the keyboard; 11.4.3.2 solve applied problems of
objectives
various subject areas.

A list can contain any sort object, even another list (sublist), which in turn
can contain sublists themselves, and so on. This is known as nested list.

You can use them to arrange data into hierarchical structures.

Create a Nested List


A nested list is created by placing a comma-separated sequence of sublists.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Access Nested List Items by Index


You can access individual items in a nested list using multiple indexes.
The indexes for the items in a nested list are illustrated as below:

Programming - 11 16
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[2])
# Prints ['cc', 'dd', ['eee', 'fff']]

print(L[2][2])
# Prints ['eee', 'fff']

print(L[2][2][0])
# Prints eee

Negative List Indexing In a Nested List


You can access a nested list by negative indexing as well.
Negative indexes count backward from the end of the list. So, L[-1] refers
to the last item, L[-2] is the second-last, and so on.
The negative indexes for the items in a nested list are illustrated as below:

Programming - 11 17
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[-3])
# Prints ['cc', 'dd', ['eee', 'fff']]

print(L[-3][-1])
# Prints ['eee', 'fff']

print(L[-3][-1][-2])
# Prints eee

Change Nested List Item Value


You can change the value of a specific item in a nested list by referring to its
index number.

L = ['a', ['bb', 'cc'], 'd']


L[1][1] = 0
print(L)
# Prints ['a', ['bb', 0], 'd']

Add items to a Nested list


To add new values to the end of the nested list, use append() method.

Programming - 11 18
L = ['a', ['bb', 'cc'], 'd']
L[1].append('xx')
print(L)
# Prints ['a', ['bb', 'cc', 'xx'], 'd']

When you want to insert an item at a specific position in a nested list,


use insert() method.

L = ['a', ['bb', 'cc'], 'd']


L[1].insert(0,'xx')
print(L)
# Prints ['a', ['xx', 'bb', 'cc'], 'd']

You can merge one list into another by using extend() method.

L = ['a', ['bb', 'cc'], 'd']


L[1].extend([1,2,3])
print(L)
# Prints ['a', ['bb', 'cc', 1, 2, 3], 'd']

Remove items from a Nested List


If you know the index of the item you want, you can use pop() method. It
modifies the list and returns the removed item.

L = ['a', ['bb', 'cc', 'dd'], 'e']


x = L[1].pop(1)
print(L)
# Prints ['a', ['bb', 'dd'], 'e']

# removed item
print(x)
# Prints cc

If you don’t need the removed value, use the del statement.

L = ['a', ['bb', 'cc', 'dd'], 'e']


del L[1][1]
print(L)
# Prints ['a', ['bb', 'dd'], 'e']

Programming - 11 19
If you’re not sure where the item is in the list, use remove() method to delete
it by value.

L = ['a', ['bb', 'cc', 'dd'], 'e']


L[1].remove('cc')
print(L)
# Prints ['a', ['bb', 'dd'], 'e']

Find Nested List Length


You can use the built-in len() function to find how many items a nested
sublist has.

L = ['a', ['bb', 'cc'], 'd']

print(len(L))
# Prints 3

print(len(L[1]))
# Prints 2

Iterate through a Nested List


To iterate over the items of a nested list, use simple for loop.

L = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]


for list in L:
for number in list:
print(number, end=' ')
# Prints 1 2 3 4 5 6 7 8 9

Consider the following example of a 3x4 matrix implemented as a list of 3


lists of length 4:

matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]

The following list comprehension will transpose rows and columns:

Programming - 11 20
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

📖 Extra Reading:
Work With Nested Lists

week 5-6 (41-44)

Dictionaries
11.2.5.1 create a dictionary; 11.2.5.2 search for data in a
Learning dictionary for a given key; 11.2.3.6 determine the difference
objectives between different data structures; 11.4.3.2 solve applied
problems of various subject areas.

Dictionaries are Python’s implementation of a data structure, generally


known as associative arrays, hashes, or hashmaps.

You can think of a dictionary as a mapping between a set of indexes (known


as keys) and a set of values. Each key maps to a value. The association of a
key and a value is called a key:value pair or sometimes an item.
As an example, we’ll build a dictionary that stores employee record.

Programming - 11 21
Create a Dictionary
You can create a dictionary by placing a comma-separated list
of key:value pairs in curly braces {} . Each key is separated from its
associated value by a colon :

# Create a dictionary to store employee record


D = {'name': 'Bob',
'age': 25,
'job': 'Dev',
'city': 'New York',
'email': 'bob@web.com'}

The dict() Constructor


You can convert two-value sequences into a dictionary with
Python’s dict() constructor. The first item in each sequence is used as the
key and the second as the value.

# Create a dictionary with a list of two-item tuples


L = [('name', 'Bob'),
('age', 25),
('job', 'Dev')]

D = dict(L)
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}

# Create a dictionary with a tuple of two-item lists


T = (['name', 'Bob'],
['age', 25],
['job', 'Dev'])

D = dict(T)
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}

When the keys are simple strings, it is sometimes easier to specify key:value
pairs using keyword arguments.

D = dict(name = 'Bob',
age = 25,
job = 'Dev')

Programming - 11 22
print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}

Other Ways to Create Dictionaries


There are lots of other ways to create a dictionary.
You can use dict() function along with the zip() function, to combine
separate lists of keys and values obtained dynamically at runtime.

# Create a dictionary with list of zipped keys/values


keys = ['name', 'age', 'job']
values = ['Bob', 25, 'Dev']

D = dict(zip(keys, values))

print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev'}

You’ll often want to create a dictionary with default values for each key.
The fromkeys() method offers a way to do this.

# Initialize dictionary with default value '0' for each key


keys = ['a', 'b', 'c']
defaultValue = 0

D = dict.fromkeys(keys,defaultValue)

print(D)
# Prints {'a': 0, 'b': 0, 'c': 0}

There is one more way to create a dictionary based on existing dictionary,


called Dictionary comprehension.

Important Properties of a Dictionary


Dictionaries are pretty straightforward, but here are a few points you should
be aware of when using them.

Keys must be unique:


A key can appear in a dictionary only once.

Even if you specify a key more than once during the creation of a dictionary,
the last value for that key becomes the associated value.

Programming - 11 23
D = {'name': 'Bob',
'age': 25,
'name': 'Jane'}
print(D)
# Prints {'name': 'Jane', 'age': 25}

Notice that the first occurrence of ‘name’ is replaced by the second one.

Key must be immutable type:


You can use any object of immutable type as dictionary keys – such as
numbers, strings, booleans or tuples.

D = {(2,2): 25,
True: 'a',
'name': 'Bob'}

An exception is raised when mutable object is used as a key.

# TypeError: unhashable type: 'list'


D = {[2,2]: 25,
'name': 'Bob'}

Value can be of any type:


There are no restrictions on dictionary values. A dictionary value can be any
type of object and can appear in a dictionary multiple times.

# values of different datatypes


D = {'a':[1,2,3],
'b':{1,2,3}}

# duplicate values
D = {'a':[1,2],
'b':[1,2],
'c':[1,2]}

Access Dictionary Items


The order of key:value pairs is not always the same. In fact, if you write the
same example on another PC, you may get a different result. In general, the
order of items in a dictionary is unpredictable.

Programming - 11 24
But this is not a problem because the items of a dictionary are not indexed
with integer indices. Instead, you use the keys to access the corresponding
values.
You can fetch a value from a dictionary by referring to its key in square
brackets [] .

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

print(D['name'])
# Prints Bob

If you refer to a key that is not in the dictionary, you’ll get an exception.

print(D['salary'])
# Triggers KeyError: 'salary'

To avoid such exception, you can use the special dictionary get() method.
This method returns the value for key if key is in the dictionary, else None , so
that this method never raises a KeyError .

# When key is present


print(D.get('name'))
# Prints Bob

# When key is absent


print(D.get('salary'))
# Prints None

Add or Update Dictionary Items


Adding or updating dictionary items is easy. Just refer to the item by its key
and assign a value. If the key is already present in the dictionary, its value is
replaced by the new one.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

D['name'] = 'Sam'

Programming - 11 25
print(D)
# Prints {'name': 'Sam', 'age': 25, 'job': 'Dev'}

If the key is new, it is added to the dictionary with its value.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

D['city'] = 'New York'


print(D)
# Prints {'name': 'Bob', 'age': 25, 'job': 'Dev', 'city': 'New York'}

Merge Two Dictionaries


Use the built-in update() method to merge the keys and values of one
dictionary into another. Note that this method blindly overwrites values of the
same key if there’s a clash.

D1 = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

D2 = {'age': 30,
'city': 'New York',
'email': 'bob@web.com'}

D1.update(D2)
print(D1)
# Prints {'name': 'Bob', 'age': 30, 'job': 'Dev',
# 'city': 'New York', 'email': 'bob@web.com'}

Remove Dictionary Items


There are several ways to remove items from a dictionary.

Remove an Item by Key


If you know the key of the item you want, you can use pop() method. It
removes the key and returns its value.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

Programming - 11 26
x = D.pop('age')
print(D)
# Prints {'name': 'Bob', 'job': 'Dev'}

# get removed value


print(x)
# Prints 25

If you don’t need the removed value, use the del statement.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

del D['age']
print(D)
# Prints {'name': 'Bob', 'job': 'Dev'}

Remove Last Inserted Item


The popitem() method removes and returns the last inserted item.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

x = D.popitem()
print(D)
# Prints {'name': 'Bob', 'age': 25}

# get removed pair


print(x)
# Prints ('job', 'Dev')

Remove all Items


To delete all keys and values from a dictionary, use clear() method.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

D.clear()
print(D)
# Prints {}

Programming - 11 27
Get All Keys, Values and Key:Value Pairs
There are three dictionary methods that return all of the dictionary’s keys,
values and key-value pairs: keys(), values(), and items(). These methods are
useful in loops that need to step through dictionary entries one by one.
All the three methods return iterable object. If you want a true list from
these methods, wrap them in a list() function.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

# get all keys


print(list(D.keys()))
# Prints ['name', 'age', 'job']

# get all values


print(list(D.values()))
# Prints ['Bob', 25, 'Dev']

# get all pairs


print(list(D.items()))
# Prints [('name', 'Bob'), ('age', 25), ('job', 'Dev')]

Iterate Through a Dictionary


If you use a dictionary in a for loop, it traverses the keys of the dictionary by
default.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

for x in D:
print(x)
# Prints name age job

To iterate over the values of a dictionary, index from key to value inside the
for loop.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

for x in D:

Programming - 11 28
print(D[x])
# Prints Bob 25 Dev

Check if a Key or Value Exists


If you want to know whether a key exists in a dictionary, use in and not
in operators with if statement.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

print('name' in D)
# Prints True
print('salary' in D)
# Prints False

To check if a certain value exists in a dictionary, you can use


method values() , which returns the values as a list, and then use
the in operator.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

print('Bob' in D.values())
# Prints True
print('Sam' in D.values())
# Prints False

Find Dictionary Length


To find how many key:value pairs a dictionary has, use len() method.

D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}

print(len(D))
# Prints 3

Python Dictionary Methods

Programming - 11 29
Python has a set of built-in methods that you can invoke on dictionary
objects.

Method Description

clear() Removes all items from the dictionary

copy() Returns a shallow copy of the dictionary

fromkeys() Creates a new dictionary with the specified keys and values

get() Returns the value of the specified key

items() Returns a list of key:value pair

keys() Returns a list of all keys from dictionary

pop() Removes and returns single dictionary item with specified key.

Removes and returns last inserted key:value pair from the


popitem()
dictionary.

Returns the value of the specified key, if present. Else, inserts the
setdefault()
key with a specified value.

update() Updates the dictionary with the specified key:value pairs

values() Returns a list of all values from dictionary

Built-in Functions with Dictionary


Python also has a set of built-in functions that you can use with dictionary
objects.

Method Description

all() Returns True if all list items are true

any() Returns True if any list item is true

len() Returns the number of items in the list

sorted() Returns a sorted list

Programming - 11 30

You might also like