Вы находитесь на странице: 1из 70

CS 101

Python

University of Jos
THIS PARTICULAR COMPILATION PUT TOGETHER BY ‘STEAMZ’
Table of Contents

1. Comments And Variables in Python ……………………..……….2


2. Numbers …………………….…………………………………………………6
3. String and sequences ………………………………………………....12
4. Lists …………………………………..………………………………………….3
5. Tuples ……………………………………………………………………..… 59
6. Dictionaries …………………………………………………………………62

1
01. Comments And Variables in
Python

Comments in Python
Comments in Python start with the hash character, #, and extend to the end of the physical line.
A comment may appear at the start of a line or following whitespace or code, but not within a
string literal. A hash character within a string literal is just a hash character.

For example:

#This is the first comment


>>> num = 1 #this is another comment
>>> text = "# This is not a comment because it's inside quotes."

Variables
A variable is something that holds a value that may change. In simplest terms, a variable is just
a box or holder that you can put a value in. You can use variables to store all kinds of stuff, but
for now, we are just going to look at storing numbers in variables.

>>> bar = 7
>>> print (bar)
7

This code creates a variable called bar , and assigns to it the integer number 7 . When we ask
Python to tell us what is stored in the variable bar , it returns that number again.

We can also change what is inside a variable.

2
For example:

>>> foo = 3
>>> print (foo)
3

>>> foo = 9
>>> print (foo)
9

>>> coo = 12
>>> print (coo)
12
>>> print (foo)
9

>>> foo = 15
>>> print (foo)
15

We declare a variable called foo , put the integer 3 in it, and verify that the assignment was
properly done. Then, we assign the integer 9 to foo , and ask again what is stored in foo .
Python has thrown away the 3 , and has replaced it with 9 . Next, we create a second variable,
which we call coo , and put 12 in it. Now we have two independent variables, coo and foo
that hold coo information, i.e., assigning a new value to one of them is not affecting the other.

You can also assign the value of a variable to be the value of another variable.

For example:

>>> red = 5
>>> blue = 10
>>> print (red, blue)
5 10

>>> yellow = red


>>> print (yellow, red, blue)
5 5 10

>>> red = blue


>>> print (yellow, red, blue)
5 10 10

3
To understand this code, keep in mind that the name of the variable is always on the left side of

the equals sign (the assignment operator), and the value of the variable on the right side of the
equals sign. First the name, then the value.
We start out declaring that red is 5 , and blue is 10 . As you can see, you can pass several
arguments to print to tell it to print multiple items on one line, separating them by spaces. As
expected, Python reports that red stores 5 , and blue holds 10 .

Now we create a third variable, called yellow . To set its value, we tell Python that we
want yellow to be whatever red is. (Remember: name to the left, value to the right.) Python
knows that red is 5 , so it also sets yellow to be 5 .

Now we're going to take the red variable, and set it to the value of the blue variable. Don't get
confused — name on the left, value on the right. Python looks up the value of blue , and finds
that it is 10 . So, Python throws away red 's old value ( 5 ), and replaces it with 10 . After this
assignment Python reports that yellow is 5 , red is 10 , and blue is 10 .

But didn't we say that yellow should be whatever value red is? The reason that yellow is
still 5 when red is 10 , is because we only said that yellow should be whatever red is at the
moment of the assignment. After Python has figured out what red is and assigned that value
to yellow , yellow doesn't care about red any more. yellow has a value now, and that
value is going to stay the same no matter what happens to red .

Variable Naming in Python

1. Variable names must start with a letter, or a connecting character such as the
underscore (_).

2. Variable names cannot start with a number, space, dollar sign ($) or any other special
character apart from underscore.

3. After the first character, Variable names can contain any combination of letters,
connecting characters, or numbers.

4. In practice, there is no limit to the number of characters an Variable names can contain.

5. Variable names in Python are case-sensitive; foo and FOO are two different identifiers.

For example:

#legal identifiers are as follows:


>>> _a = 7
>>> ______2_w = 9
>>> this_is_a_very_detailed_name_for_an_identifier = 9
#illegal identifiers are as follows:

4
>>> $c = 7
SyntaxError: invalid syntax
>>> _$ = 9
SyntaxError: invalid syntax
>>> 7g = 8
SyntaxError: invalid syntax
>>> e# = 29
SyntaxError: invalid syntax

5
02. Numbers

Python Programming/Numbers
Python 2.x supports 4 numeric types - int, long, float and complex. Of these, the long type has
been dropped in Python 3.x - the int type is now of unlimited length by default.
You don’t have to specify what type of variable you want; Python does that automatically.

• Int: The basic integer type in python, equivalent to the hardware 'c long' for the platform you
are using in Python 2.x, unlimited in length in Python 3.x.
• Long: Integer type with unlimited length. In python 2.2 and later, Ints are automatically
turned into long ints when they overflow. Dropped since Python 3.0, use int type instead.
• Float: This is a binary floating point number. Longs and Ints are automatically converted to
floats when a float is used in an expression, and with the true-division / operator.
• Complex: This is a complex number consisting of two floats. Complex literals are written as
a + bj where a and b are floating-point numbers denoting the real and imaginary parts
respectively.

In general, the number types are automatically 'up cast' in this order:
Int → Long → Float → Complex.
The farther to the right you go, the higher the precedence.

>>> x = 5
>>> type(x)
<class 'int'>
>>> x = 187687654564658970978909869576453
>>> type(x)
<class 'long'>
>>> x = 1.34763
>>> type(x)
<class 'float'>
>>> x = 5 + 2j
>>> type(x)
<class 'complex'>

Expression
6
A sequence of operands and operators
A legal combination of operands (data objects) and operators

Syntax
<object><operator><object>

If we type the expression 2 + 3 and it will evaluate it and print out 5 on the screen.
For example:

>>> 2 + 3
5

Every programming language has a Syntax, Static Semantics and Semantics


1. Syntax tells which sequence of characters and symbols constitute a well formed (not
necessarily meaningful) statement.
There are rules that govern a legal expression in a language
For example:

>>> 3 + 4 # is syntactically correct <operand><operator><operand>


5
>> 3 3 #is not syntactically correct <operand>< ><operand>

2. Static Semantics tells which well-formed string have meaning

For example:

>>> 3/'abc'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
3/'abc'
TypeError: unsupported operand type(s) for /: 'int' and 'str'

# 3/'abc' is syntactical correct <operand><operator><operand>


# But it is not semantically correct because it is not well formed
# you cannot divide a number by a string

3. Semantics tells us what the meaning is


i.e. Looks only at those strings that are both Synthetically correct and static
semantically correct and assigns meaning to them

For example:

7
>>> 3 + 2 # both syntactically and static semantically correct
5 # semantically correct so evaluates to 5 i.e. assigns meaning

Errors
These are things that might happen if we design a program that does not do what we
want it to do.
1. Crash stop running and produces some powerful indication that it did not run
2. Never Stop (infinite loop) your program keeps running and can never stop
3. Run To Completion and Produces a wrong Answer This is the worse type of error
because it can cost lives.

Operators
1. Addition (+) used to add two or more numbers or string, if values added are integers
the result will be an integer. If any of the values added are float, the result will be a
float. If values added are strings the result will be a concatenation of strings. When
the addition is used to add strings, the operator is said to be overloaded.
2. Subtraction (-) used to subtract two or more numbers
3. Division (/) used to divide two or more numbers. The result of divisions is somewhat
confusing. In Python 2.x, using the / operator on two integers will return another
integer, using floor division. For example, 5/2 will give you 2. You have to specify
one of the operands as a float to get true division, e.g. 5/2. or 5./2 (the dot specifies
you want to work with float) will yield 2.5. In Python 3.x, the result of using the /
operator is always true division (you can ask for floor division explicitly by using the
//).
4. Remainder (%) used to get the remainder part of a division
5. Power (**) used to find the exponent of a number
6. Assignment (=) binds a name to an object (or value) used to equate a value to a
variable
7. Parentheses (( )) used to group values
Comparison Operator
8. Equality (= =) used to compare values
9. Not Equals to (!=)
10. Greater (>)
11. Less (<)
12. Greater or Equals to (>=)
13. Less or Equals to (<=)
Logical Operators
14. and
15. or
16. not

8
Operator Precedence
1. ( )
2. **
3. * & /
4. + & -
5. =

Using Python as a Calculator Along with the


Operators
The interpreter acts as a simple calculator: you can type an expression at it and it will write the
value. Expression syntax is straightforward: the operators +, -, * and / work just like a calculator;
parentheses (()) can be used for grouping.

For example:

>>> 2+2
4
>>> 12-5*2 #this means 5*2=10, 12-10 = 2
20
>>> (28-2*7)/7
2.0
>>> 8/5
1.6
>>>5%2
1
>>> 6 > 7
False
>>> 8 == 8
True
>>> True and True
True
>>> True or False
True
>>> not False
True

This illustrates the behavior of the / operator

9
>>> 5/2 # in python 2.x 5/2 will give you 2
2.5
>>> 5/2. # in python 2.x you needed to do 5/2. to get 2.5
2.5
>>> 5./2 # or 5./2 to get 2.5
2.5
>>> 5//2 # in python 3.x you have to do a floor division to get whole
number
>>>5//2.0
2.0

In interactive mode, the last printed expression is assigned to the variable _. This means that
when you are using Python as a desk calculator, it is somewhat easier to continue calculations.
For example:

>>> tax = 12.5 / 100 #assignment


>>> tax
0.125
>>> price = 100.50
>>> price*tax
12.5625
>>> price + _
113.0625
>>> round(_,2)
113.06

Another example:

>>> black = 1
>>> brown = 2
>>> green = 3
>>> eyecolor = black
>>> eyecolor
1
>>> print(brown)
2
>>>print(green brown)
32

10
>>>
3 2 print(green,brown,black)
1
>>> eyecolor = green
>>> eyecolor == black
False
>>> eyecolor == green
True

Update Pattern
Used to changes the value of a variable based upon the original value.
Another example:

>>> counter = 0
>>> counter = counter + 1
>>> counter = counter + 1
>>> counter
2
>>> counter += 1
>>>print(counter)
3

Throwaway Pattern
This is a mistake attempt of the update pattern. In the update pattern, we use the original value
of the variable to compute the new value of the variable.
For example:

>>> counter = 0
>>> counter + 1
>>> counter
0

11
03. Strings And Sequences

Sequences
Sequences allow you to store multiple values in an organized and efficient fashion.
There are three kinds of sequences in Python: strings, lists and tuples.
Dictionaries and sets are containers for sequential data.

String Literal
Literal means write something that belongs to a particular type in a programming language.
For example, we have Number Literals, String Literals, List Literals etc..
Number Literal is how to write a Number in python.

For Examples:
>>> 55 #this is the Literal for int in decimal
55
>>> 0o17 #this is the Literal for int in octal Python 2.x Octal is 017
15

>>> 0x41 #this is the Literal for int in hexadecimal


65
>>> 40.45 #this is how to write a float
40.45
>>> 10E5 #this is also another Literal for float
1000000.0

>>> 10e-4 #this is also another Literal for float


0.001

String Literal is how to write a String in python e.g. “hello”,


‘hello’ Either single or double quotes may be used to delimit
string constants. i.e. Strings are either enclosed in double quote or
single quote.

12
Example of String Constants:
>>> 'hey now'
'hey now'
>>>"hey now"
'hey now'
>>> print("hay now")
hay now

>>> print('hay now')

hay now
>>> "buky said, "hey now" to me" #this is wrong
SyntaxError: invalid syntax

>>> 'buky said, "hey noe" to me' #this is correct


'buky said, "hey noe" to me'

>>> "buky said, \"hey now\" to me" #this is also correct


'buky said, "hey now" to me'

>>> '''buky said, "hey now" to me''' #this is also correct


'buky said, "hey now" to me'
#you can write multiple lines using 3 single quotes
>>> s = ''' may mother
any your mother went
to the market'''

>>> s
'may mother\nany your mother\nwent to the market'

Comments
A comment starts with a hash character (#) that is not part of a string literal, and ends at the
end of the physical line. A comment signifies the end of the logical line unless the implicit
line joining rules are invoked. Comments are ignored by the syntax; they are not tokens.

For Example

13
>>> #This is a comment and its meant to be ignored by the compiler

>>> #But users like you need comments for better understanding
>>> s = 'Johnny' # This is a string assigned to a variable named s
>>> print(s) # this is a print statement that prints the content of string
s Johnny

Escape Sequence
A sequence of characters that does not represent itself when used inside a character or string
literal, but is translated into another character or a sequence of characters that may be
difficult or impossible to represent directly.

ESCAPE SEQUENCE MEANING

\n New line

\t Horizontal Tab

\v Vertical Tab

\\ Back slash

\" Double Quotation Mark

\' Single Quotation Mark

\b Back space

\a Bell

\r Carriage return

\f Form feed

For Example
>>> s = 'some escape sequences are \t\n\'\"'
>>> s
'some escape sequences are \t\n\'"'
>>> print('come\nhere')
come here

>>> print('come\there')
come here

14
15
Input and Print command
The input command is used to enter values from the keyboard while the print command is used
to output values on the screen.

For Example
>>> age = input()#Input without string in it
50 #Lets assume user typed 50 from keyboard
>>> age
'50'
>>> name = input("What is your name? ") #Input with string in it
What is your name? Johnny #Lets assume user typed 'Johnny' from keyboard
>>> name
'Johnny'
>>> print(name name)
johnnyjohnny

>>> print(name,name)
johnny johnny

'int'>

How to embed values in strings

To embed a particular value in a string make use of %s.

The value corresponding the % in the print statement is replaced with %s in the string.

When using more than one place holders be sure to wrap the replacement values in ( )
>>> year = 50
>>> say = 'i am %s years old'
>>> print(say % year)
i am 50 years old

>>> print('%s students attended my lecture today' % 50)


50 students attended my lecture today
>>> print('i am %s years old plus %s' % (50,5))
i am 50 years old plus 5
String operations Equality
(==)

Two strings are equal if they have exactly the same contents, meaning that they are both the
same length and each character has a one-to-one positional correspondence.

Examples:
>>> a = 'hello'; b = 'hello' # Assign 'hello' to a and b.
>>> a == b # check for equality
True
>>> a == 'hello' #
True
>>> a == "hello" # (choice of delimiter is unimportant)
True

>>> a == 'hello ' # (extra space)


False
>>> a == 'Hello' # (wrong case)
False

is Operator
Python uses the is operator to test the identity of strings and any two objects in general.

For Example:
>>> a = 'hello'; b = 'hello' # Assign 'hello' to a and b.
>>> a is b # check for equality: is a equals b

True
>>> print(a is b)
True

17
Overloaded Operators
There are two operators which can be used on both numbers and strings -- addition and
multiplication. These operators are said to be overloaded because the can be used on both
numbers and strings.

String addition is just another name for concatenation. String multiplication is repetitive
addition, or repetitive concatenation.

For Example:

>>> c = 'a'
>>> c + 'b'
'ab'
>>> c * 5
'aaaaa'

Containment
There is a simple operator 'in' that returns True if the first operand is contained in the second.
This also works on substrings

>>> x = 'hello'
>>> y = 'ell'
>>> x in y
False
>>> y in x
True
>>> print(y in x)
True

18
19
Indexing and Slicing
Indexes are numbered from 0 to n-1 where n is the number of items (or characters), and they are
positioned between the items:

H e l l o , _ w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Much like arrays in other languages, the individual characters in a string can be accessed by an
integer representing its position in the string. The first character in string s would be s[0] and the
nth character would be at s[n-1].

For Example:
>>> "Hello, world!"[0]
'H'
>>> "Hello, world!"[1]
'e'

>>> "Hello, world!"[2]


'l'

>>> "Hello, world!"[3]


'l'

>>> "Hello, world!"[4]


'o'
>>> "Hello, world!"[-2]
'd'
>>> "Hello, world!"[-9]
'o'
>>> "Hello, world!"[-13]
'H'
>>> "Hello, world!"[-1]
'!'

20
Another Example:

>>> s = "Xanadu"
>>> s[1]
'a'

Python also indexes the arrays backwards, using negative numbers. The last character has index -
1, the second to last character has index -2, and so on.

>>> s[-4]
'n'

Another feature of slices is that if the beginning or end is left empty, it will default to the first or
last index, depending on context:

We can also use "slices" to access a substring of s. s[a:b] will give us a string starting with s[a]
and ending with s[b-1].

To understand slices, it's easiest not to count the elements themselves. It is a bit like counting not
on your fingers, but in the spaces between them.

The list is indexed like this:

Element: 1 2 3 4
Index: 0 1 2 3 4
-4 -3 -2 -1

So, when we ask for the [1:4] slice, that means we start at index 1, and end at index 4-1, and take
everything in between them.

For Example:

21
>>> s[1:4]
'ana'

>>> s[0:0]
''
>>> s[2:]
'nadu'

>>> s[:3]
'Xan'
>>> s[0:6]
'Xanadu'
>>> s[0:100]
'Xanadu'
>>> s[:]
'Xanadu'
>>> s[::]
'Xanadu'
>>> s[0:4:2] #read from 0 to 3 jump 2 steps
'Xn'
>>> s[::1] #read from beginning to end
'Xanadu'
>>> s[::2]
'Xnd'

You can also use negative numbers in slices:

>>> print s[-2:]


'du'
>>> s[::-1] #read the reverse way
'udanaX'
>>> s[::-2] #read opposite way and jump two steps
'uaa'
>>> s[-4::-1] #read from -4 to the end in the opposite way Xanadu is naX 'naX'

22
None of these are assignable.
>>> print(s)
Xanadu

>>> s[0] = 'J'


Traceback (most recent call last):
File "<stdin>", line 1, in ?

TypeError: object does not support item assignment

>>> s[1:3] = "up"


Traceback (most recent call last):
File "<stdin>", line 1, in ?

TypeError: object does not support slice assignment


>>> print s

String methods

There are a number of methods or built-in string functions:

• capitalize
• center
• count
• decode encode
• endswith
• expandtabs
• find
• index
• isalnum
• isalpha
• isdigit
• islower

23
• isspace istitle
• isupper
• join
• ljust
• lower
• lstrip
• replace
• rfind
• rindex
• rjust
• rstrip
• split
• splitlines
• startswith
• strip
• swapcase
• title
• translate
• upper
• zfill

Only emphasized items will be covered.

is*
isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), and istitle() fit into this category.

The length of the string object being compared must be at least 1, or the is* methods will return
False. In other words, a string object of len(string) == 0, is considered "empty", or False.

isalnum returns True if the string is entirely composed of alphabetic and/or numeric characters
(i.e. no punctuation or special character).

For Example:

24
#a contains some special character space

>>> a = "hello wold"


>>> a.isalnum()
False
>>> "Common".isalnum()
True

isalpha and isdigit work similarly for alphabetic characters or numeric characters only.

For Example:
>>> '1234'.isalpha()
False
>>> '1234'.isdigit()
True

>>> 'abcd'.isalpha()
True

>>> 'abcd'.isdigit()
False
>>> c = 'abcd1234'
>>> c.isalpha()
False

>>> c.isdigit()
False

>>> c.isalnum()
True

isspace returns True if the string is composed entirely of whitespace.

For Example:

>>> ' '.isspace()


True
>>> ''.isspace()
25
False
>>> 'my name'.isdigit() False

islower, isupper, and istitle return True if the string is in lowercase, uppercase, or titlecase
respectively. Uncased characters are "allowed", such as digits, but there must be at least one
cased character in the string object in order to return True. Titlecase means the first cased
character of each word is uppercase, and any immediately following cased characters are
lowercase. Curiously, 'Y2K'.istitle() returns True. That is because uppercase characters can only
follow uncased characters. Likewise, lowercase characters can only follow uppercase or
lowercase characters. Hint: whitespace is uncased.

For Example:
>>> "MY".isupper()
True

>>> "MY".islower()
False

>>> "my".isupper()
False

>>> "my".islower()
True
>>> "Proper".istitle()
True
>>> "Proper Casing".istitle()
True

>>> "Proper2Casing".istitle()
True
>>> "ProperCasing".istitle()
False

Title, Upper, Lower, Swapcase, Capitalize


Returns the string converted to title case, upper case, lower case, inverts case, or capitalizes,
respectively.

26
The title method capitalizes the first letter of each word in the string (and makes the rest lower
case). Words are identified as substrings of alphabetic characters that are separated by
nonalphabetic characters, such as digits, or whitespace. This can lead to some unexpected
behavior. For example, the string "x1x" will be converted to "X1X" instead of "X1x".

The capitalize method is like title except that it considers the entire string to be a word. (i.e. it
makes the first character upper case and the rest lower case)

The swapcase method makes all uppercase letters lowercase and vice versa.

For Example:
>>> "joneses".title()
'Joneses'
>>> "joneses".capitalize()
'Joneses'
>>> 'y2k'.title()
'Y2K'
>>> 'y2k'.capitalize()
'Y2k'
>>> 'john'.upper()
'JOHN'

>>> 'JOHN'.lower()
'john'
>>> 'JoHn'.swapcase()
'jOhN'

count
Returns the number of the specified substrings in the string.

Note count() is case-sensitive


For Example:

27
>>> s = 'Hello, world'
>>> s.count('o') #print the number of 'o's in 'Hello, World' (2)
2

>>> s = 'HELLO, WORLD'


>>> s.count('o') #print the number of lowercase 'o's in 'HELLO,
WORLD' (0)
0

strip, rstrip, istrip


Returns a copy of the string with the leading (lstrip) and trailing (rstrip) whitespace removed.

strip removes both.

>>> s = '\t Hello, world\n\t'

>>> print(s)
Hello World
>>> print s.strip()
Hello, world
>>> print s.lstrip()
Hello, world
>>> print s.rstrip() Hello, world

Other than the leading and trailing tabs and newlines Strip methods can also be used to remove
other types of characters.

Scripts are python programs you can save and execute, while programs types on the python
prompt otherwise known as the shell cannot be saved.

Steps to save your python codes them as a script

28
1. Click on File Tab on the Menu Bar Select New File (A Text Editor opens where you
can type your python codes)

2. Click on File Tab on the Menu Bar Select Save (to save your code to whatever
location in your computer with a .py extension)

3. Click on Run Tab on the Menu Bar Select Run Module (to execute you code and
output on the screen)

Note that the text editor for the script does not have the three angle brackets (>>>) like that
of the shell command prompt and it does not print anything on the screen unless you use the
print command.

Example of writing python code on a script text editor to demonstrate how the strip() method
works
import string s =
'www.wikibooks.org'
print(s)

print(s.strip('w')) # Removes all w's from outside


print(s.strip(string.ascii_lowercase)) # Removes all lowercase letters from
outside 2.x was just lowercase

print(s.strip(string.printable)) # Removes all printable characters

Outputs:
www.wikibooks.org
.wikibooks.org
.wikibooks.

Note that string.lowercase and string.printable require an import string statement

Rewriting the same code on a shell command promp


>>> import string
>>> s = 'www.wikibooks.org'
>>> s #you don’t have 2 use d print command on d shell to output something

29
'www.wikibooks.org' >>>
print(s) www.wikibooks.org
>>> print(s.strip('w'))

.wikibooks.org
>>> print(s.strip(string.ascii_lowercase))
.wikibooks.

>>> print(s.strip(string.printable))

ljust, rjust, center


left, right or center justifies a string into a given field size (the rest is padded with spaces).
>>> s = 'foo'
>>> s
'foo'
>>> s.ljust(7)
'foo '

>>> s.rjust(7)
' foo'
>>> s.center(7)
' foo '

join
Joins together the given sequence with the string as separator:

30
>>> s = 'common'
>>> ' '.join(c)
'c o m m o n'

>>> '*'.join(s)
'c*o*m*m*o*n'
>>> seq = ['1', '2', '3', '4', '5']
>>> ' '.join(seq)
'1 2 3 4 5'

>>> '+'.join(seq)
'1+2+3+4+5'

A map may be helpful here: (it converts numbers in seq into strings)
>>> seq = [1,2,3,4,5] >>> '
'.join(map(str, seq))

'1 2 3 4 5'

Now arbitrary objects may be in seq instead of just strings.

find, index, rfind, rindex


The find and index methods return the index of the first found occurrence of the given
subsequence. If it is not found, find returns -1 but index raises a ValueError. rfind and rindex are
the same as find and index except that they search through the string from right to left (i.e. they
find the last occurrence)
>>> s = 'Hello, world'
>>> s.find('l')
2
>>> s.index('l')
2

>>> s.rfind('l')
10
>>> s.rindex('l')
10
>>> s.find('z')
-1
>>> s[s.index('l'):]

31
'llo, world'
>>> s.rfind('l')
10
>>> s[:s.rindex('l')]
'Hello, wor'
>>> s[s.index('l'):s.rindex('l')]
'llo, wor'
>>> s[s.find('z'):]
'd'

Because Python strings accept negative subscripts, index is probably better used in situations like
the one shown because using find instead would yield an unintended value.

replace
Replace works just like it sounds. It returns a copy of the string with all occurrences of the first
parameter replaced with the second parameter.

>>> 'Hello, world'.replace('o', 'X')


'HellX, wXrld'

Or, using variable assignment:


myString = 'Hello, world'
myNewString = myString.replace('o', 'X')
print(myString) print(myNewString)

Outputs:

Hello, world
HellX, wXrld

Notice, the original variable (myString) remains unchanged after the call replace to .

32
expandtabs
Replaces tabs with the appropriate number of spaces (default number of spaces per tab = 8; this
can be changed by passing the tab size as an argument).
>>> tabString = '\t'
>>> tabString
'\t'
>>> tab = tabString.expandtabs()
>>> tab
' '
>>> tabLength = len(tab)
>>> tabLength
8
>>> s = 'abcdefg\tabc\ta'
>>> s
'abcdefg\tabc\ta'
>>> print(s)
abcdefg abc a

>>> s.expandtabs()
'abcdefg abc a'
>>> len(s.expandtabs())
17

Example of expandtabs() on a Script

s = 'abcdefg\tabc\ta'
print(s) print(len(s))
t = s.expandtabs()
print(t) print(len(t))

Outputs:

33
abcdefg abc a
13 abcdefg abc
a
17

Notice how (although these both look the same) the second string (t) has a different length
because each tab is represented by spaces not tab characters.

To use a tab size of 4 instead of 8:

v = s.expandtabs(4)
print(v) print(len(v))

Outputs:

abcdefg abc a
13

Please note each tab is not always counted as eight spaces. Rather a tab "pushes" the count to the
next multiple of eight.

For example of tab on a script:


s = '\t\t'
print(s.expandtabs().replace(' ', '*'))
print(len(s.expandtabs()))

Outputs:

****************
16

Another Example of tab on a script:


s = 'abc\tabc\tabc'

34
print s.expandtabs().replace(' ', '*')
print len(s.expandtabs())

Outputs:

abc*****abc*****abc
19

split, splitlines
The split method returns a list of the words in the string. It can take a separator argument to use
instead of whitespace.

>>> s = 'Hello, world'


>>> s.split() #default is space i.e split whenever you find a space
['Hello,', 'world']
>>> s.split('l')
['He', '', 'o, wor', 'd']

Note that in neither case is the separator included in the split strings, but empty strings are
allowed.

The splitlines method breaks a multiline string into many single line strings. It is analogous to
split('\n') (but accepts '\r' and '\r\n' as delimiters as well) except that if the string ends in a newline
character, splitlines ignores that final character (see example).

>>> s = """
... One line
... Two lines
... Red lines
... Blue lines
... Green lines

35
... """
>>> s.split('\n')
['', 'One line', 'Two lines', 'Red lines', 'Blue lines', 'Green lines', '']
>>> s.splitlines()
['', 'One line', 'Two lines', 'Red lines', 'Blue lines', 'Green lines']

36
Type Casting
Conversion of an object from one type to another by using the name of that type as a function
Type casting is also known as type conversion For Example:
>>> float(3) #casting an int into a float
3.0
>>> int(4.5) #casting a float into an int
4
>>> 'a'+3 #static semantics is not correct cannot add a str and an int
TypeError: Can't convert 'int' object to str implicitly
>>> 'a'+str(3) #convert int into string before you concatenate them
'a3'

>>> int('3') #casting a int_string into an int


3
>>> int('a') #cannot cast a letter_string into an int
ValueError: invalid literal for int() with base 10: 'a'
>>> int('3.1') #cannot cast a float_string into an int
ValueError: invalid literal for int() with base 10: '0.3'
>>> float('3.1') #casting a float_string into a float
3.1
>>> int(float('3.1')) #casting a float_string into a float then into int
3

Another Example:
>>> name = input("What's your name? ")
What's your name? Frank >>>
age = input("Your age? ")

Your age? 30
>>> print("So, you are already " + str(age) + " years old, " + name + "!")
So, you are already 30 years old, Frank!

37
Another Example:

>>> age = input('How old are you? ')


How old are you? 30
>>> print(age, type(age))
30 <class 'str'>

>>> age = int(input('How old are you? '))


How old are you? 40
>>> print(age, type(age))
40 class 'str'>

38
04. List
List Creation

There are two different ways to make a list in Python. The first is through assignment
("statically"), the second is using list comprehensions ("actively").

Plain creation
To make a static list of items, write them between square brackets.

For example:
>>> # this is how to declare a list and it is printed out automatically
>>> [ 1,2,3,"This is a list",'c' ]
[1, 2, 3, 'This is a list', 'c']
>>>[] # this is an empty list
[]
>>>
>>> # a list can contain different data values
>>> # such as Numbers, Boolean, String, List, Map, Set, Object etc.
>>> # look at the example below
>>> myList = [1, 2.3, 4j, True, "hello", []] #list values assigned to myList
>>>

>>> myList # this is one of the ways to print out a list


[1, 2.3, 4j, True, 'hello', []]
>>> print(myList) # this is another way to printout a list
[1, 2.3, 4j, True, 'hello', []]

Observations:The list contains items of different data types: integer, string, and even another
List.

Creation of a new list whose members are constructed from non-literal expressions:
>>> a = 2
>>> b = 3

39
>>> myList = [a+b, b*a, len(["a","b"])]#len():Length AKA size AKA item
count
>>>myList
[5, 6, 2]

List comprehensions
Using list comprehension, you describe the process using which the list should be created. To do
that, the list is broken into two pieces. The first is a picture of what each element will look like,
and the second is what you do to get it.

For instance, let's say we have a list of words:


>>> listOfWords = ["this","is","a","list","of","words"] #list of strings

To take the first letter of each word and make a list out of it using list comprehension,

We can do this:
>>> listOfWords = ["this","is","a","list","of","words"]
>>> items = [ word[0] for word in listOfWords ]
>>> print(items)
['t', 'i', 'a', 'l', 'o', 'w']
>>> items = [ word[0:2] for word in listOfWords ]
>>> print(items)
['th', 'is', 'a', 'li', 'of', 'wo']

List comprehension supports more than one for statement. It will evaluate the items in all of the
objects sequentially and will loop over the shorter objects if one object is longer than the rest.
>>> item = [x+y for x in 'cat' for y in 'pot']
>>> print(item)
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
>>>
>>> item = [x+y for x in 'cow' for y in 'mo']
>>> item
['cm', 'co', 'om', 'oo', 'wm', 'wo']

40
List comprehension supports an if statement, to only include members into the list that fulfill a
certain condition:
>>> print([x+y for x in 'cat' for y in 'pot'])
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
>>> print([x+y for x in 'cat' for y in 'pot' if x != 't' and y != 'o' ])
['cp', 'ct', 'ap', 'at']
>>> print([x+y for x in 'cat' for y in 'pot' if x != 't' or y != 'o' ]) ['cp',
'co', 'ct', 'ap', 'ao', 'at', 'tp', 'tt']

In version 2.x, Python's list comprehension does not define a scope. Any variables that are bound
in an evaluation remain bound to whatever they were last bound to when the evaluation was
completed. In version 3.x Python's list comprehension uses local variables:
>>> print([x+y for x in 'cat' for y in 'pot'])
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
>>> print x, y #print statement; python version 2.x
t t #Output

>>> print(x, y) #print statement; python version 3.x


NameError: name 'x' is not defined #Outputs error bcos x & y were not leaked

This is exactly the same as if the comprehension had been expanded into an explicitly-nested
group of one or more 'for' statements and 0 or more 'if' statements.

List Concatenation / Combining lists

Lists can be combined in several ways. The easiest is just to 'add' them using the (+) operator.

For instance:
>>> [1,2] + [3,4]
[1, 2, 3, 4]

41
Although String is also a sequence like List but they can not be added
>>> 'buky'+['c','o','m','e']
TypeError: Can't convert 'list' object to str implicitly

List creation shortcuts / Repetitive Concatenation of List


You can multiply a list by using the multiplication (*) operator.

You are also indirectly initializing the list to a particular size, with an initial value for each

element For Example:


>>> zeros=[0]*5 #initializing list to length 5 with all zeros
>>> print(zeros)
[0, 0, 0, 0, 0]

This works for any data type:


>>> foos=['foo']*3
>>> print(foos)
['foo', 'foo', 'foo']

But there is a caveat. When building a new list by repetitive multiplication, Python copies each
item by reference. This poses a problem for mutable items, for instance in a multidimensional
array where each element is itself a list. You'd guess that the easy way to generate a two
dimensional array would be:
>>> listoflists=[ [0]*4 ] *5
>>> print(listoflists)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> listoflists[0][2]=1
>>> print(listoflists)
[[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]

What's happening here is that Python is using the same reference to the inner list as the elements
of the outer list. Another way of looking at this issue is to examine how Python sees the above
definition:

42
>>> innerlist=[0]*4
>>> listoflists=[innerlist]*5
>>> print(listoflists)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> innerlist[2]=1
>>> print(listoflists)
[[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]

Assuming the above effect is not what you intend;

One way around this issue is to use static list, another way is to use list comprehensions:
>>> # this is cumbersome but easier to declare a 2dim array
>>> listoflists = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0]] #static list
>>> # or this is a better and faster way to write declare a 2dim array
>>> listoflists = [[0]*4 for i in range(5)] #list comprehension
>>> listoflists
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> listoflists[0][2]=1
>>> print(listoflists)
[[0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

List Attributes

The len() method is a built in-function used to find the length of a list.

This built in methods can be is also applicable to almost all sequences such as string, tuple
and map.

43
For Example:
>>> len([1,2,3])
3
>>> a = [1,2,3,4]
>>> len( a )
4
>>> len("come") #len() mtd can also be used to determine the length of string
4

Aggregates

There are some built-in functions for arithmetic aggregates over lists. These include minimum,
maximum, and sum:
>>> nums = [8, 1, 4, 17, 28, 165, 7]
>>> max(nums)
165

>>> min(nums)
1
>>> list = ['5', '2', '3', 'q', 'p']
>>> sorted(list)
['2', '3', '5', 'p', 'q']
>>> list
['5', '2', '3', 'q', 'p']
>>>
>>> list = [1, 2, 3, 4]
>>> list = [1, 2, 3, 4]
>>> print(max(list), min(list), sum(list))
4 1 10
>>> average = sum(list) / float(len(list)) # Provided the list is non-empty
#The float above ensures the division is a float one rather than integer one.

>>> print(average)
2.5

44
The max and min functions also apply to lists of strings, returning maximum and minimum with
respect to alphabetical order:
>>> list = ["aa", "ab"]
Print( max(list), min(list) ) # Prints "ab aa"

Sorted

The sorted() method is also another built-in function in python that returns the sorted list
without sorting the list in place
>>> list = ['5', '2', '3', 'q', 'p']
>>> sorted(list) # sorts a copy of the list
['2', '3', '5', 'p', 'q']
>>> list # but does not sort the original list
['5', '2', '3', 'q', 'p']
>>>
>>> sorted('easyhoss') #sorted can also convert a string into a sorted list
['a', 'e', 'h', 'o', 's', 's', 's', 'y']

The ‘in’ operator

The operator 'in' is used for two purposes; either to check if a value is in a list returning true or
false , or to iterate over every item in a list in a for loop.
>>> family = ['dad', 'mum', 'bro']
>>> 'sis' in family # checks if a value exists in the list False

>>> 'mum' in family # also checks if a value exists in the list True

>>> l = [0, 1, 2, 3, 4]
>>> 3 in l
True

45
>>> 18 in l
False
>>> list = [1, 2, 3, 4]
>>> if 3 in list: # also checks if a value exists in the list
print(True)

True
>>>
>>>
>>>

>>> numList = [0, 1, 2, 3, 4]


>>> for x in numList:

>>> print (x)


0
1
2
3
4

Changing a list item


The assignment (=) operator is used to change the value of an element in a list

For example:
>>> num = [2, 4, 6, 8, 10]
>>> num[2] = 77
>>> print(num)
[2, 4, 77, 8, 10]

Keeping only items in a list satisfying a condition, and thus removing the items that do not
satisfy it:
>>> list = [1, 2, 3, 4]
>>> newlist = [item for item in list if item >2]
>>> print(newlist)
[3, 4]

46
Clearing list items

Items on a list can be cleared either by using the del keyword, pop(), or remove()
method. The pop() and remove() methods will be discussed later on this course.

Using the del keyword


The del keyword is used to delete an element from a list

For example:
>>> num = [0, 1, 2, 3, 4, 5]
>>> num.insert(2, 66)
>>> num
[0, 1, 66, 2, 3, 4, 5]
>>> del num[2] # Remove the 3rd element; an alternative to
list.pop(2)
>>> print(num)
[0, 1, 2, 3, 4, 5]
>>> del num[:] # Clear a list We will talk more on slicing lists
>>> num # print empty list
[]

IMPORTANT NOTE

Clearing a list:
del list1[:] # Clear a list
list1 = [] # Not really clear but rather assign to a new empty list

Clearing using a proper approach makes a difference when the list is passed as an argument:
def workingClear(ilist):
del ilist[:] def
brokenClear(ilist):

ilist = [] # Lets ilist point to a new list, losing the reference to the
argument list

47
list1=[1, 2]; workingClear(list1); print(list1) # OUTPUT: []
list1=[1, 2]; brokenClear(list1); print(list1) # OUTPUT: [1, 2]

Copying

Copying AKA cloning of lists:

Making a shallow copy:


>>> # Shallow Copy
>>> list1 = [1,2,3,4]
>>> list2 = list1 # Copy using assignment operator (=)
>>> list2[0]=2 # Modifies the original list i.e. list1 as well as list2
>>> list2
[2, 2, 3, 4] >>>
list1

[2, 2, 3, 4]
>>> list3 = [1,2,3,4]
>>>
>>> list4 = list3[:]# Copy using "[:]"
>>> list4[0]=2 # Only affects list4, not list3
>>> list4
[2, 2, 3, 4] >>>
list3

[1, 2, 3, 4]

The above does not make a deep copy, which has the following consequence:
>>> list1 = [1, [2, 3]] # Notice that this is a nested list
>>> list2 = list1[:] # Also a shallow copy in this case
>>> list2[1][0] = 4 # Modifies the 2nd item of list1 as well >>>
list1

[1, [4, 3]]

48
Making a deep copy:
>>> import copy
>>> list1 = [1, [2, 3]] # Notice the second item being a nested list
>>> list2 = copy.deepcopy(list1) # A deep copy
>>> list2[1][0] = 4 # Leaves the 2nd item of list1 unmodified
>>> Print(list2)
[1, [4, 3]]

>>> Print(list1)
[1, [2, 3]]

Comparing lists

Lists can be compared for equality.


>>> [1,2] == [1,2]
True

>>> [1,2] == [3,4]


False

Lists can be compared using a less-than operator, which uses lexicographical order:
>>> [1, 2] < [2, 1]
True

>>> [2, 2] < [2, 1]


False
>>> ["a", "b"] < ["b", "a"]
True

49
Some methods in Python that can be used to manipulate
lists

EXTEND
list.extend(list)
This is another way to combine lists instead of using the (+) operator.

For example:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.extend(b)
>>> print a
[1, 2, 3, 4, 5, 6]

APPEND
list.append(x) used to add a value to
the end of the list.

For example:
>>> x = [2, 18, 30]
>>> x.append(14) # appending a number to a list
>>> x
[2, 18, 30, 14]
>>> x.append([20, 22]) # appending another list to a list
>>> x
[2, 18, 30, 14, [20, 22]]
>>> y = [2, 18, 30, 14]
>>> y.extend([20, 22]) # use extend if intention was to concatenate 2 lists
>>> print(y)
[2, 18, 30, 14, 20, 22]

However, [20,22] is an element of the list, and not part of the list. append always adds one
element only to the end of a list. So if the intention was to concatenate two lists, always use
extend.

50
INSERT
list.insert(i, x)
Inserts an item at a given position. The first argument i is the index of the element before which to
insert and the second x is the value to append to the list. Which is equivalent to append but the
difference is that insert can insert a value in any position of the list while append is always at the
end of the list.

For example:
>>> x = [0, 1, 2, 3, 4, 5]
>>> x.insert(3, 66)
>>> print(x)
[0, 1, 2, 3, 66, 4, 5]

REMOVE
list.remove(x)
Removes the first item from the list whose value is x. (Remove an element by
value) It is an error if there is no such item.

For Example:
>>> s=['ade', 'ada', 'olu', 'ali', 'ada', 'ayo']
>>> s.remove('ada') # Removes only the 1st occurrence of "ada"
>>> s
=['ade', 'olu', 'ali', 'ada', 'ayo']

INDEX
list.index(x)
Returns the index in the list of the first item whose value is
x. It is an error if there is no such item.

For example:
>>> num = [0, 1, 2, 3, 4, 5]
>>> num[len('ab')] = 66
>>> num.index(66)
2

>>> num.index(77)
ValueError: 77 is not in list

51
POP
list.pop( ) or list.pop(x)
Remove the item in the list at the index i and return it. (Remove an element by
index) If i is not given, remove the last item in the list and return it.

For Example:
>>> list = [1, 2, 3, 4]
>>> a = list.pop(0) # Remove the first item , which is the item at
index 0
>>> list
[2, 3, 4]
>>> a
1
>>> b = list.pop() # Remove the last item
>>>list
[2, 3]
>>> b
4

COUNT
list.count(x)
Returns the number of times x appears on the list.

For Example:
>>> s=['ade', 'ada', 'olu', 'ali', 'ada', 'ayo']
>>> s.count('ada')
2

52
REVERSE
list.reverse()
Reverses the elements of the list in place.

For Example:
>>> num = [1, 2, 3, 4, 5]
>>> num.reverse()
>>> num
[5, 4, 3, 2, 1]

53
SORT
list.sort()

Sort the items of the list in place. Sorting lists is easy with a sort method.
>>> list = ['2', '3', '1', 'a', 'b']
>>> list.sort()
>>> list
['1', '2', '3', 'a', 'b']

Note that the list is sorted in place, and the sort() method returns None to emphasize this
side effect.

There are some more sort parameters: sort(cmp,key,reverse) cmp : method

to be used for sorting key : function to be executed with key element.

List is sorted by return-value of the function reverse : sort(reverse=True) or


sort(reverse=False)

Slicing Lists /Getting pieces of lists (slices)


Continuous slices
Like strings, lists can be indexed and sliced.

For Example:
>>> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list

54
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[0:10]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[0:]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[:10]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[:]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[-10:]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list[-10:-1]

[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list[-11:-1]

[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list[4:8]
[4, 5, 6, 7]
>>> list[-7:-3]
[3, 4, 5, 6]
>>> list[-1:-10]
[]
>>> list[-10:0]
[]

Another Example:
>>> list = [2, 4, "usurp", 9.0,"n"]
>>> list[2]
'usurp'
>>> list[3:]
[9.0, 'n']

Much like the slice of a string is a substring, the slice of a list is a list. However, lists differ from
strings in that we can assign new values to the items in a list.
55
>>> list[1] = 17
>>> list
[2, 17, 'usurp', 9.0,'n']

We can even assign new values to slices of the lists, which don't even have to be the same length
>>> list[1:4] = ["opportunistic", "elk"]
>>> list
[2, 'opportunistic', 'elk', 'n']

It's even possible to append things onto the end of lists by assigning to an empty slice:
>>> list[:0] = [3.14,2.71]
>>> list
[3.14, 2.71, 2, 'opportunistic', 'elk', 'n']

You can also completely change contents of a list:


>>> list[:] = ['new', 'list', 'contents']
>>> list
['new', 'list', 'contents']

On the right-hand side of assignment statement can be any iterable type:


>>> list[:2] = ('element',('t',),[])
>>> list
['element', ('t',), [], 'contents']

With slicing you can create copy of list because slice returns a new list:
>>> original = [1, 'element', []]
>>> listCopy = original[:]

>>> listCopy
[1, 'element', []]
>>> listCopy.append('new element')
>>> listCopy
[1, 'element', [], 'new element']
>>> original
[1, 'element', []]

56
but this is shallow copy and contains references to elements from original list, so be careful with
mutable types:
>>> listCopy[2].append('something')
>>> original
[1, 'element', ['something']]

Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get every n-th
occurrence of a list, one would use the :: operator. The syntax is a:b:n where a and b-1 are the
start and end of the slice to be operated upon and n is the stepsize.
>>> list = [i for i in range(10) ]
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
list[::1]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list[-


10::1]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[:-1:1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list[10:0:-1] #can go from 10 to 0 in the opposite direction
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list[0:10:-1] # cannot go from 0 to 10 in the opposite way is empty list
[]

>>> list[0:10:1] # can go from 0 to 10 in the +ve direction


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[10:0:-2] # can go from 10 to 0 in –ve way jumping 2 steps
[9, 7, 5, 3, 1]
>>> list[-10:-1:-1] # cannot go from -10 to -1 in the –ve way
[]

>>> list[-10:-1:1] # can go from -10 to -1 in the +ve way


[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list[-1:-10:-1] # can go from -1 to -10 in the –ve way

57
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list[-1:-10:1] # cannot go from -1 to -10 in the +ve way
[]

>>> list[::2]
[0, 2, 4, 6, 8]
>>> list[1:7:2] #print from 1 to 7 jump 2 steps
[1, 3, 5]

58
05. Tuples

Tuples
A tuple is the same thing as a list only that it cannot be changed. Elements in a tuple cannot be
appended, removed or updated. The only thing we can do with a tuple is to get their value and index.

Think of a tuple as Read Only while a list can be thought of as Read, Write, Update and Delete.

Tuples are enclosed in parentheses, () For Example:

>>> () # this is an empty tuple


()
>>> 41, 42, 43, 44, 45 # One way to write a tuple is to separate them by comma
(41, 42, 43, 44, 45)
>>> (41, 42, 43, 44, 45) # Another way in to enclose them in parentheses
(41, 42, 43, 44, 45)
>>> t = (41, 42, 43, 44, 45) # Assigning a tuple to a variable t
>>> t # Another way to say print the content of variable t
(41, 42, 43, 44, 45)
>>> t[2]
43

Using Some Python In-Built methods in Tuple

Most of the in-built methods used on the list can also be used on tuples; like the len, sum, max, min,
sorted, …

For Example:
>>> t = (41, 42, 43, 44, 45)
>>> t
(41, 42, 43, 44, 45)

59
>>> len(t) # gets the length of tuple
6
>>> sum(t) # sums all the values of the tuple
259
>>> max(t) # gets the maximum value of contents in tuple
45

>>> min(t) # gets the minimum value of contents in tuple


41
>>> sorted(t) # makes a list copy of the tuple
[41, 42, 43, 44, 44, 45]
>>> l = sorted(t)#makes a list copy of the tuple and assigns it to a variable l
>>> l
[41, 42, 43, 44, 44, 45]
>>> t
(41, 42, 43, 44, 45)

Methods in Python that can be used to manipulate a Tuple


Only two methods can be used for Tuples; count and index.

COUNT
tuple.count(x)
The count method is used to count how many times x appears in the tuple.

For Example:

>>> t = (41, 42, 43, 44, 45, 44)


>>> t.count(44)
2

INDEX
tuple.index(x)

The index method is used to find out the index of the first occurrence of x in the tuple.

For Example:

60
>>> t = (41, 42, 43, 44, 45, 44)
>>> t.index(44)
3

Casting Further

Conversion of one type into another type.

You can cast a string into a list or tuple and vice versa.

For Example:

>>> list('come') # casting a string into a list


['c', 'o', 'm', 'e']
>>> tuple('come') # casting a string into a tuple
('c', 'o', 'm', 'e')
>>> str(('c', 'o', 'm', 'e')) # casting a tuple into a string
"('c', 'o', 'm', 'e')"
>>> str(['c', 'o', 'm', 'e']) # casting a list into a string
"['c', 'o', 'm', 'e']"

You can cast a list into a tuple and vice versa.

For Example:
>>> t = (41, 42, 43, 44, 45, 44) >>>
list(t) # casting a tuple into a list

[41, 42, 43, 44, 45, 44]


>>> l = [1, 2, 3, 4, 5, 4]
>>> tuple(l) # casting a list into a tuple
(1, 2, 3, 4, 5, 4)

61
06. Dictionaries

Dictionaries
A dictionary in Python is a collection of unordered values accessed by key rather than by index. The
keys have to be hash-able: integers, floating point numbers, strings, tuples, and frozen sets are
hashable, while lists, dictionaries, and sets other than frozen-sets are not.

Dictionary uses key to look up items and value to display the value of the item, just like the regular
dictionary where you can youse a word to lookup the meaning of a word. Dictionaries are enclosed in
curly braces, {}

For Example:
>>> {} # this is an empty dictionary
{}
>>> # Create an empty dictionary and assigning it to a variable
>>> familyMembers1 = {}
>>> familyMembers1
{}
>>> # non-empty dictionary
>>> {"Dad": "Gim", "Mum": "Pearl", "Bro": "Ben", "Sis": "Vicky"}
{'Bro': 'Ben', 'Sis': 'Vicky', 'Mum': 'Pearl', 'Dad': 'Gim'}
>>># Creates a non-empty dict and assigning it to a variable familyMembers2
>>> familyMembers2={'Bro': 'Ben', 'Sis': 'Vicky', 'Mum': 'Pearl', 'Dad': 'Gim'}
>>> familyMembers2 # Prints out a non-empty dictionary
{'Bro': 'Ben', 'Sis': 'Vicky', 'Mum': 'Pearl', 'Dad': 'Gim'}
>>> print(familyMembers2) # Also Prints out a non-empty dictionary
{'Bro': 'Ben', 'Sis': 'Vicky', 'Mum': 'Pearl', 'Dad': 'Gim'}

62
# To assign a value to empty dictionary familyMembers1
>>> familyMembers1['Dad'] = 'Gim'
>>>print(familyMembers1)

{'Dad': 'Gim'}
>>>

Dictionaries can also be created from the built-in dictionary method dict(), just like every other datatype
in python can be created by calling there datatype names as a built-in method.

For Example:
>>> a = int()#creating an integer from the in-built int method
>>> a #default value is 0
0
>>> b = complex()#creating a complex number from in-built complex method
>>> b #default value is 0j

0j
>>> c = float() #creating a float from in-built float method
>>> c #default value is 0.0
0.0
>>> d = bool() #creating a boolean from in-built bool method
>>> d #default value is False
False
>>>
>>> e = str() #creating an empty string from the in-built string method
>>> e #default value is empty string
''
>>> f = list() #creating an empty list from the in-built list method
>>> f
[]
>>> g = dict() #creating an empty dictionary from the in-built dict method
>>> g
{}
>>> # initialize age from a list of tuples
>>> age = dict([("Mum", 34), ('Dad', 54)])
>>> age # Prints out non-empty dictionary
{'Mum': 34, 'Dad': 54}

63
>>># Another way to create a non-empty dict and assign it to familyMembers
>>> familyMembers = dict(Dad="Gim", Mum="Kim", Sis="Rim")
>>> familyMembers
{'Mum': 'Kim', 'Dad': 'Gim', 'Sis': 'Rim'}
>>> # To print the value of Sis in familyMembers
>>> familyMembers["Sis"]
'Rim'

Dictionaries can also be created by zipping two sequences using the in-built zip() method in the in-built
dict() method.

For Example:

>>> seq1 = ('a', 'b', 'c', 'd') # Tuple


>>> seq2 = [1, 2, 3, 4] # List
>>> seq3 = dict(zip(seq1, seq2)) # Dictionary formed by zipping Tuple & List
>>> seq3 # Print dict
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
>>> seq4 = dict(zip(seq2, seq1)) # Dictionary formed by zipping List & Tuple
>>> seq4 # Print dict
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

Comparing Dictionaries using the Equality Operator (==)


Two Dictionaries can be compared using the equality operator For

Example:

>>> # Dictionary assigned to variable info


>>> info = {'city':'Paris', 'age':38, (102,1650,1601):'A matrix coordinate'}
>>> seq = [('city','Paris'), ('age', 38), ((102,1650,1601),'A matrix
coordinate')] # List of Tuples assigned to variable seq

>>> info # Print dict


{'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'} >>>
dict(seq) # converts list into dict and Print

64
{'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'}
>>> d = dict(seq) # converts list into dict and assign to variable d
>>> d[(102,1650,1601)] # Get the value of this key (102,1650,1601)
'A matrix coordinate'
>>> # shortcut to get the value of this key (102,1650,1601)
>>> dict(seq)[(102,1650,1601)]
'A matrix coordinate'
>>> info == dict(seq) # Using the equality operator to test for equality True

Changing the value of a key using the Assignment Operator (=)


The content of a key can be changed using assignment For

Example:

>>>
>>> info = {'a':1,'b':2, 'cat':'Fluffers'}
>>> info
{'a':1,'b':2, 'cat':'Fluffers'}
>>> # key 'cat' contain some value 'Fluffers' which is changed to 'Willy'
>>> info['cat'] = 'Willy'
>>> info
{'a': 1, 'cat': 'Willy', 'b': 2}
>>>

The assignment operator can also be used to copy perform a deep copy of a dictionary
For Example:
>>>
>>> info = {'a': 1,'b': 2, 'cat': 'Willy'}
>>> >>> d = info # using = to perform a deep copy
>>> d
{'a': 1, 'cat': 'Willy', 'b': 2}

65
>>> # once you change the content of dict d you also change the content of info
>>> d['cat'] = 'Jark'
>>> d
{'a': 1, 'cat': 'Jark', 'b': 2} >>>
info

{'a': 1, 'cat': 'Jark', 'b': 2}

Using the del keyword to delete contents from a Dictionary


The del is a keyword in python that can be used to delete contents from the dictionary.

For Example:

>>>
>>> fruits = {'lemons': 6, 'grapes': 5, 'pears': 4, 'apples': 1, 'oranges': 3}
>>> fruits
{'lemons': 6, 'grapes': 5, 'pears': 4, 'apples': 1, 'oranges': 3}
>>> del fruits['pears'] # using the del keyword to delete an item from the dict
>>> fruits

{'lemons': 6, 'grapes': 5, 'oranges': 3, 'apples': 1}


>>>

Some methods in Python that can be used to manipulate a


Dictionary

CLEAR
dict.clear()
The clear method is used to empty the contents of a dictionary

For Example:

>>>
>>> info = {'a':1,'b':2, 'cat':'Fluffers'} # dict assigned to variable info

66
>>> info # prints the info dict which contains keys and values
{'a': 1, 'cat': 'Fluffers', 'b': 2}
>>> info.clear()# using the clear method to empty all the contents in the dic
>>> info # prints an empty dict
{}

COPY
dict.copy()
The copy method is used to copy the contents of one dictionary to another

For Example:

>>> info = {'a': 1,'b': 2, 'cat': 'Willy'}


>>> d = info.copy() # using the copy mtd to copy content
>>> d
{'a': 1, 'cat': 'Willy', 'b': 2}
>>> d['cat'] = 'Jark'
>>> d
{'a': 1, 'cat': 'Jark', 'b': 2}
>>> info
{'a': 1, 'cat': 'Willy', 'b': 2}

GET
dict.get(k)
The get method is used to get the value of the key k in the dictionary.

For Example:

>>> info = {'a': 1,'b': 2, 'cat': 'Willy'}


>>>info
{'a': 1,'b': 2, 'cat': 'Willy'}

67
>>> info.get('b') # outputs the value of key
2
>>> info
{'a': 1,'b': 2, 'cat': 'Willy'}

POP
dict.pop(k)
The pop method is used to remove the value of the key k in the dictionary.

For Example:

>>> info = {'a': 1,'b': 2, 'cat': 'Willy'}


>>>info
{'a': 1,'b': 2, 'cat': 'Willy'}
>>> info.pop('b') # outputs the value of key and removes content from the dict
2
>>> info
{'a': 1, 'cat': 'Willy'}

UPDATE
dict.update(dict)
The update method is used to combine two dictionaries by using the update method of the primary
dictionary. Note that the update method will merge existing elements if they conflict.

For Example:
>>> d = {'apples': 1, 'oranges': 3, 'pears': 2}
>>> e = {'pears': 4, 'grapes': 5, 'lemons': 6}
>>> d.update(e) # Updates d with values from e
>>> d
{'lemons': 6, 'grapes': 5, 'pears': 4, 'apples': 1, 'oranges': 3} >>>
e

{'lemons': 6, 'grapes': 5, 'pears': 4}

68
KEYS
dict.keys()
The key method is used to print a list of keys in the dict.

For Example:

>>> d = {'apples': 1, 'oranges': 3, 'pears': 2}


>>> d.keys()
['pears', 'apples', 'oranges']

VALUES
dict.values()
The value method is used to print a list of values in the dict.

For Example:

>>> d = {'apples': 1, 'oranges': 3, 'pears': 2}


>>> d.values()
[2, 1, 3]

69

Вам также может понравиться