Programming - 11
Programming - 11
Programming - 11
3-quarter
week-1 (33-34)
The list data type has some more methods. Here are all of the methods of
list objects:
list.extend(iterable) Extend the list by appending all the items from the
iterable. Equivalent to a[len(a):] = iterable .
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.
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
📖 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)
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).
📖 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)
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).
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.
>>> '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:
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.
str.index(sub[, start[, end]]) Like find() , but raise ValueError when the
substring is not found.
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.
>>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
Programming - 11 8
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False
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.
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
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'
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.
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', '']
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:
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'
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:
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:
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).
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.
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
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
Programming - 11 18
L = ['a', ['bb', 'cc'], 'd']
L[1].append('xx')
print(L)
# Prints ['a', ['bb', 'cc', 'xx'], 'd']
You can merge one list into another by using extend() method.
# removed item
print(x)
# Prints cc
If you don’t need the removed value, use the del statement.
Programming - 11 19
If you’re not sure where the item is in the list, use remove() method to delete
it by value.
print(len(L))
# Prints 3
print(len(L[1]))
# Prints 2
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
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
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.
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 :
D = dict(L)
print(D)
# Prints {'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'}
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.
D = dict.fromkeys(keys,defaultValue)
print(D)
# Prints {'a': 0, 'b': 0, 'c': 0}
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.
D = {(2,2): 25,
True: 'a',
'name': 'Bob'}
# duplicate values
D = {'a':[1,2],
'b':[1,2],
'c':[1,2]}
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 .
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
D['name'] = 'Sam'
Programming - 11 25
print(D)
# Prints {'name': 'Sam', 'age': 25, 'job': 'Dev'}
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
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'}
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
Programming - 11 26
x = D.pop('age')
print(D)
# Prints {'name': 'Bob', 'job': 'Dev'}
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'}
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
x = D.popitem()
print(D)
# Prints {'name': 'Bob', 'age': 25}
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'}
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
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
print('name' in D)
# Prints True
print('salary' in D)
# Prints False
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
print('Bob' in D.values())
# Prints True
print('Sam' in D.values())
# Prints False
D = {'name': 'Bob',
'age': 25,
'job': 'Dev'}
print(len(D))
# Prints 3
Programming - 11 29
Python has a set of built-in methods that you can invoke on dictionary
objects.
Method Description
fromkeys() Creates a new dictionary with the specified keys and values
pop() Removes and returns single dictionary item with specified key.
Returns the value of the specified key, if present. Else, inserts the
setdefault()
key with a specified value.
Method Description
Programming - 11 30