Unit I: Introduction To Python
Unit I: Introduction To Python
Unit I: Introduction To Python
Introduction to Python:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL).
This tutorial gives enough understanding on Python programming language.
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Characteristics of Python:
Following are important characteristics of Python Programming −
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java
Applications of Python:
As mentioned before, Python is one of the most widely used language over the web.
I'm going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
History of Python:
Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are
listed below −
It provides very high-level dynamic data types and supports dynamic type checking.
Open a terminal window and type "python" to find out if it is already installed and
which version is installed.
Win 9x/NT/2000
OS/2
PalmOS
Windows CE
Acorn/RISC OS
BeOS
Amiga
VMS/OpenVMS
QNX
VxWorks
Psion
Python has also been ported to the Java and .NET virtual machines
Getting Python:
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python https://www.python.org/
If the binary code for your platform is not available, you need a C compiler to compile the
source code manually. Compiling the source code offers more flexibility in terms of choice
of features that you require in your installation.
Follow the link to download zipped source code available for Unix/Linux.
make
make install
Windows Installation:
Here are the steps to install Python on Windows machine.
Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
To use this installer python-XYZ.msi, the Windows system must support Microsoft
Installer 2.0. Save the installer file to your local machine and then run it to find out if
your machine supports MSI.
Macintosh Installation:
Recent Macs come with Python installed, but it may be several years out of date.
See http://www.python.org/download/mac/ for instructions on getting the current version
along with extra tools to support development on the Mac. For older Mac OS's before Mac
OS X 10.3 (released in 2003), MacPython is available.
Jack Jansen maintains it and you can have full access to the entire documentation at
his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation
details for Mac OS installation.
Setting up PATH
Programs and other executable files can be in many directories, so operating systems
provide a search path that lists the directories that the OS searches for executables.
The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and
other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case
sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter
from any particular directory, you must add the Python directory to your path.
To add the Python directory to the path for a particular session in Unix −
In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.
To add the Python directory to the path for a particular session in Windows −
1
PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where to locate the
module files imported into a program. It should include the Python source library
directory and the directories containing Python source code. PYTHONPATH is
sometimes preset by the Python installer.
2
PYTHONSTARTUP
It contains the path of an initialization file containing Python source code. It is executed
every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains
commands that load utilities or modify PYTHONPATH.
3 PYTHONCASEOK
4 PYTHONHOME
Running Python:
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-
line interpreter or shell window.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
1 -d
2 -O
3 -S
4 -v
5
-X
disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.
6 -c cmd
7 file
Macintosh − The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.
If you are not able to set up the environment properly, then you can take help from your
system admin. Make sure the Python environment is properly set up and working perfectly
fine.
Note − All the examples given in subsequent chapters are executed with Python 2.4.3
version available on CentOS flavor of Linux.
We already have set up Python Programming environment online, so that you can execute
all the available examples online at the same time when you are learning theory. Feel free to
modify any example and execute it online.
Type the following text at the Python prompt and press the Enter −
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
If you
>>> print are running
"Hello, new version of Python, then you would need to use print statement
Python!"
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this
Type "help", "copyright", "credits" or "license" for more information.
produces the following result −
>>>
Hello, Python!
Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a test.py file −
We
printassume
"Hello,that you have Python interpreter set in PATH variable. Now, try to run this
Python!"
program as follows −
This produces
$ python the following result −
test.py
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file −
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run
#!/usr/bin/python
this program as follows −
printproduces
"Hello, Python!"
This the following
$ chmod +x test.py # Thisresult −
is to make file executable
$./test.py
Hello, Python!
Python Identifiers:
Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
Starting an identifier with a single leading underscore indicates that the identifier is
private.
If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Reserved Words:
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the Python
keywords contain lowercase letters only.
assert finally or
elif in while
else is with
Variable:
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign (=)
is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand
to the right of the = operator is the value stored in the variable. For example −
#!/usr/bin/python
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously. For
example
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple variables. For
example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Comments in Python:
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the Python
interpreter ignores them.
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments:
'''
This is a multiline
comment.
'''
A line containing only whitespace, possibly with a comment, is known as a blank line
and Python totally ignores it.
The following line of the program displays the prompt, the statement saying “Press
the enter key to exit”, and waits for the user to take action −
Here, "\n\n" is used to create two new lines before displaying the actual line. Once
#!/usr/bin/python
the user presses the key,
raw_input("\n\nPress the program
the enter ends. This is a nice trick to keep a console window
key to exit.")
open until the user is done with an application.
The semicolon ( ; ) allows multiple statements on the single line given that neither
statement starts a new code block. Here is a sample snip using the semicolon −
A group of individual statements, which make a single code block are called suites in
Python. Compound or complex statements, such as if, while, def, and class require a header
line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : )
and are followed by one or more lines which make up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
Many programs can be run to provide you with some basic information about how
they should be run. Python enables you to do this with -h −
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding enviro
-c cmd : program passed in as string (terminates option list)
-d: debug output from parser (also PYTHONDEBUG=x)
-E: ignore environment variables (such as PYTHONPATH)
-h: print this help message and exit
Indentation In python:
Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly
enforced.
The number of spaces in the indentation is variable, but all statements within the block must
be indented the same amount. For example −
if True:
print "True"
else:
print "False"
if True:Thus, in Python all the continuous lines indented with same number of spaces would
form
print a block. The following example has various statement blocks −
"Answer"
Note − Do not try to understand the logic at this point of time. Just make sure you
print "True"various blocks even if they are without braces.
understood
else:
#!/usr/bin/python import sys
print
try:
# "Answer"
open file stream
file = open(file_name, "w") except IOError:
print "There was an error writing to", file_name
Multi-Line Statements:
Statements in Python typically end with a new line. Python does, however, allow the
use of the line continuation character (\) to denote that the line should continue. For example
total = item_one + \
item_two + \
item_three
Quotation in Python:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the
following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Operator:
Operators are the constructs which can manipulate the value of operands.Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
- Subtraction Subtracts right hand operand from left hand operand. a–b=-
10
% Modulus Divides left hand operand by right hand operand and returns remainder b%a=
0
// Floor Division - The division of operands where the result is the 9//2 = 4
quotient in which the digits after the decimal point are removed. But if and
9.0//2.0
= 4.0, -
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
== If the values of two operands are equal, then the condition becomes true. (a == b)
is not
true.
!= If values of two operands are not equal, then condition becomes true. (a != b)
is true.
<> If values of two operands are not equal, then condition becomes true. (a <> b)
is true.
This is
similar
to !=
operator.
> If the value of left operand is greater than the value of right operand, then (a > b) is
condition becomes true. not true.
>= If the value of left operand is greater than or equal to the value of right (a >= b)
operand, then condition becomes true. is not
true.
<= If the value of left operand is less than or equal to the value of right (a <= b)
operand, then condition becomes true. is true.
= Assigns values from right side operands to left side operand c=a+b
assigns
value of a
+ b into c
+= Add AND It adds right operand to the left operand and assign the result to left c += a is
operand equivalent
to c = c +
a
-= Subtract AND It subtracts right operand from the left operand and assign the result c -= a is
to left operand equivalent
to c = c -
a
/= Divide AND It divides left operand with the right operand and assign the result c /= a is
to left operand equivalent
to c = c /
a
%= Modulus It takes modulus using two operands and assign the result to left c %= a is
AND operand equivalent
to c = c %
a
//= Floor It performs floor division on operators and assign value to the left c //= a is
Division operand equivalent
to c = c //
a
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;
and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101
respectively. Following table lists out the bitwise operators supported by Python language
with an example each in those, we use the above two variables (a and b) as operands −
b = 0000 1101
~a = 1100 0011
& Binary AND Operator copies a bit to the result if it exists in both operands (a & b)
(means
0000 1100)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49
(means
0011 0001)
<< Binary Left Shift The left operands value is moved left by the number of bits a << 2 =
specified by the right operand. 240 (means
1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of bits a >> 2 = 15
specified by the right operand. (means
0000 1111)
and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.
or Logical OR If any of the two operands are non-zero then condition becomes (a or b)
true. is true.
not Logical NOT Used to reverse the logical state of its operand. Not(a
and b) is
false.
not in Evaluates to true if it does not finds a variable in the specified sequence and x not in
false otherwise. y, here
not in
results in
a 1 if x is
not a
member
of
sequence
y.
Identity operators compare the memory locations of two objects. There are two
Identity operators explained below −
is not Evaluates to false if the variables on either side of the operator point to x is not y,
the same object and true otherwise. here is
not results in
1 if id(x) is
not equal to
id(y).
The following table lists all operators from highest precedence to lowest.
1 **
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
4 +-
5
>> <<
6
&
Bitwise 'AND'
7 ^|
8
<= < > >=
Comparison operators
9 <> == !=
Equality operators
10
= %= /= //= -= += *= **=
Assignment operators
11
is is not
Identity operators
Membership operators
13 not or and
Logical operators
The data stored in memory can be of many types. For example, a person's age is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and
the storage method for each of them.
Numbers
String
List
Tuple
Dictionary
Python Numbers:
Number data types store numeric values. They are immutable data types, means that
changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del var
del var_a, var_b
int (signed integers) − They are often called just integers or ints, are positive or
negative whole numbers with no decimal point.
long (long integers ) − Also called longs, they are integers of unlimited size, written
like integers and followed by an uppercase or lowercase L.
float (floating point real values) − Also called floats, they represent real numbers
and are written with a decimal point dividing the integer and fractional parts. Floats
may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 =
2.5 x 102 = 250).
complex (complex numbers) − are of the form a + bJ, where a and b are floats and J
(or j) represents the square root of -1 (which is an imaginary number). The real part
of the number is a, and the imaginary part is b. Complex numbers are not used much
in Python programming.
Examples:
Here are some examples of numbers
Python allows you to use a lowercase L with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
A complex number consists of an ordered pair of real floating point numbers denoted
by a + bj, where a is the real part and b is the imaginary part of the complex number.
Type complex(x) to convert x to a complex number with real part x and imaginary
part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and
imaginary part y. x and y are numeric expressions
1 abs(x)
2 ceil(x)
3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
6 floor(x)
7 log(x)
8 log10(x)
10 min(x1, x2,...)
11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as
x. The integer part is returned as a float.
12 pow(x, y)
13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from zero as a tie-
breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
14 sqrt(x)
Random numbers are used for games, simulations, testing, security, and privacy
applications. Python includes following functions that are commonly used.
1 choice(seq)
3 random()
A random float r, such that 0 is less than or equal to r and r is less than 1
4 seed([x])
Sets the integer starting value used in generating random numbers. Call this function
before calling any other random module function. Returns None.
5 shuffle(lst)
6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y
Trigonometric Functions:
1 acos(x)
2 asin(x)
3 atan(x)
4 atan2(y, x)
5 cos(x)
6 hypot(x, y)
7 sin(x)
8 tan(x)
9 degrees(x)
10 radians(x)
Mathematical Constants:
2 e
Python Strings:
Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example −
Python does not support a character type; these are treated as strings of length one,
thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring. For example −
You can "update" an existing string by (re)assigning a variable to another string. The
new value can be related to its previous value or to a completely different string altogether.
For example −
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\s 0x20 Space
\t 0x09 Tab
\x Character x
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
* Repetition - Creates new strings, concatenating multiple copies of the a*2 will
same string give -
HelloHello
[] Slice - Gives the character from the given index a[1] will
give e
[:] Range Slice - Gives the characters from the given range a[1:4] will
give ell
not in Membership - Returns true if a character does not exist in the given M not in a
string will give 1
r/R Raw String - Suppresses actual meaning of Escape characters. The print r'\n'
syntax for raw strings is exactly the same as for normal strings with the prints \n and
exception of the raw string operator, the letter "r," which precedes the print
One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf() family.
Following is a simple example −
Here is the list of complete set of symbols which can be used along with % −
%c character
Other supported symbols and functionality are listed in the following table −
Symbol Functionality
- left justification
m.n. m is the minimum total width and n is the number of digits to display
after the decimal point (if appl.)
Triple Quotes:
Python's triple quotes comes to the rescue by allowing strings to span multiple lines,
including verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
When the above code is executed, it produces the following result. Note how every
#!/usr/bin/python
single
para_strspecial character
= """this is a longhas been
string converted
that to its printed form, right down to the last
is made up
NEWLINE at the
of several lines andend of the string
non-printable betweensuch
characters the "up." and closing triple quotes. Also note
that
as
TAB ( \t ) and they will show up that way when
displayed. NEWLINEs within the string, whether
explicitly given like this within the brackets [ \n ], or just
a NEWLINE within the variable assignment will also
show up.
TAB ( ) and they will show up that way when displayed. NEWLINEs within the string,
whether explicitly given like this within the brackets [ ], or just a NEWLINE within the
variable assignment will also show up.
Raw strings do not treat the backslash as a special character at all. Every character
you put into a raw string stays the way you wrote it −
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings
are stored as 16-bit Unicode. This allows for a more varied set of characters, including
special characters from most languages in the world. I'll restrict my treatment of Unicode
strings to the following −
1 capitalize()
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
Counts how many times str occurs in string or in a substring of string if starting index beg
and ending index end are given.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the
default string encoding.
5 encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless
errors is given with 'ignore' or 'replace'.
Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with suffix; returns true if so and false otherwise.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.
Determine if str occurs in string or in a substring of string if starting index beg and ending
index end are given returns index if found and -1 otherwise.
10 isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric and false
otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise.
12 isdigit()
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
17 isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
18 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string,
with separator string.
19 len(string)
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width
columns.
21 lower()
22 lstrip()
23 maketrans()
24 max(str)
Replaces all occurrences of old in string with new or at most max occurrences if max given.
27 rfind(str, beg=0,end=len(string))
29 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width
columns.
30 rstrip()
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed.
33 startswith(str, beg=0,end=len(string))
34 strip([chars])
35 swapcase()
36 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest
are lowercase.
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del
string.
38 upper()
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for
numbers, zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise.
The list is a most versatile datatype available in Python which can be written as a list
of comma-separated values (items) between square brackets. Important thing about a list is
that items in a list need not be of the same type.
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with the append()
method. For example −
To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know. For example
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior
chapter.
Because lists are sequences, indexing and slicing work the same way for lists as they
do for strings.
1 cmp(list1, list2)
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
1 list.append(obj)
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
Python Tuples:
A tuple is a collection of objects which ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is
only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
Updating Tuples:
Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following example demonstrates −
This produces the following result. Note an exception raised, this is because after del
#!/usr/bin/python
tup tuple
tup = does not
('physics', exist any more
'chemistry', 1997,−
2000); print tup;
del tup;
print "After deleting tup :
"; print tup;
Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in
the prior chapter −
Because tuples are sequences, indexing and slicing work the same way for tuples as
they do for strings. Assuming following input −
No Enclosing Delimiters:
1 cmp(tuple1, tuple2)
2 len(tuple)
3 max(tuple)
4 min(tuple)
5 tuple(seq)
Python Dictionary:
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without any
items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such as
strings, numbers, or tuples.
To access dictionary elements, you can use the familiar square brackets along with
the key to obtain its value. Following is a simple example −
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an
error as follows −
Updating Dictionary:
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown below in the simple example −
You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example −
This produces the following result. Note that an exception is raised because after del
#!/usr/bin/python
dict
dict dictionary
= {'Name':does not'Age':
'Zara', exist 7,
any more −
'Class': 'First'}
del dict['Name']; # remove entry with key
dict['Age']:
'Name' dict.clear();
Traceback (most recent# call
remove
last):all entries in
dict
File "test.py", line 8, in <module>
delprint
dict ;"dict['Age']:
# delete",entire
dict['Age'];
dictionary print
TypeError: 'type'"dict['Age']: ",
object is unsubscriptable
dict['Age']
Note − del() method is discussed in subsequent section.
Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for the keys.
(a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins. For example
−
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example −
1 cmp(dict1, dict2)
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
3 str(dict)
Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.
1 dict.clear()
2 dict.copy()
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
5 dict.has_key(key)
6 dict.items()
7 dict.keys()
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
10 dict.values()
Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.
1 int(x [,base])
2
long(x [,base] )
3 float(x)
4
complex(real [,imag])
5 str(x)
6
repr(x)
7 eval(str)
8 tuple(s)
Converts s to a tuple.
9
list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11
dict(d)
12 frozenset(s)
13
chr(x)
14 unichr(x)
15
ord(x)
16 hex(x)
17 oct(x)