Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 39

UNIT-2

Programming with Python

S T R I NGS
T UP L E S
L I S T S
2
Programming
Strings

• Strings in Python have type str


• They represent sequence of characters
– Python does not have a type corresponding to character.
• Strings are enclosed in single quotes(') or double
quotes(“)
– Both are equivalent
• Backslash (\) is used to escape quotes and special
characters
3
Programming
Strings

• More readable when print is used

4
Programming
Length of a String

• len function gives the length of a string

\n is a single character:
the special character
representing newline 5
Programming
Concatenate and Repeat

• In Python, + and * operations have special


meaning when operating on strings
• + is used for concatenation of (two) strings
• * is used to repeat a string, an int number of
time
• Function/Operator Overloading

6
Programming
Concatenate and Repeat

7
Programming
Indexing

• Strings can be indexed


• First character has index 0

8
Programming
Indexing

• Negative indices start counting from the right


• Negatives indices start from -1
• -1 means last, -2 second last, ...

9
Programming
Indexing
• Using an index that is too large or too small results
in “index out of range” error

10
Programming
Slicing
• To obtain a substring
• s[start:end] means substring of s starting at index
start and ending at index end-1
• s[0:len(s)] is same as s
• Both start and end are optional
– If start is omitted, it defaults to 0
– If end is omitted, it defaults to the length of string
• s[:] is same as s[0:len(s)], that is same as s
11
Programming
Slicing

Programming
More Slicing

Understanding Indices for slicing


A c a d s
0 1 2 3 4 5
-5 -4 -3 -2 -1
Programming
A c a d s
Out of Range Slicing 0
-5
1
-4
2
-3
3
-2
4
-1

• Out of range indices are ignored for slicing


• when start and end have the same sign, if start >=end,
empty slice is returned
Why?

14
Programming
Tuples
• A tuple consists of a number of values separated by
commas

• Empty and Singleton Tuples


15
Programming
Nested Tuples

• Tuples can be nested

• Note that course tuple is copied into student.


– Changing course does not affect student

16
Programming
Length of a Tuple
• len function gives the length of a tuple

17
Programming
More Operations on Tuples
• Tuples can be concatenated, repeated, indexed and
sliced

18
Programming
Unpacking Sequences

• Strings and Tuples are examples of sequences


– Indexing, slicing, concatenation, repetition
operations applicable on sequences
• Sequence Unpacking operation can be applied to
sequences to get the components
– Multiple assignment statement
– LHS and RHS must have equal length

19
Programming
Unpacking Sequences

( )
20
Programming
Lists

• Ordered sequence of values


• Written as a sequence of comma-separated values
between square brackets
• Values can be of different types
– usually the items all have the same type

21
Programming
Lists
• List is also a sequence type
– Sequence operations are applicable

22
Programming
Lists
• List is also a sequence type
– Sequence operations are applicable

Repetition

( )

23
Programming
More Operations on Lists

• L.append(x) • L.pop()
• L.extend(seq) • L.index(x)
• L.insert(i, x) • L.count(x)
• L.remove(x) • L.sort()
• L.pop(i) • L.reverse()
x is any value, seq is a sequence value (list, string, tuple, …),
i is an integer value 24
Programming
Mutable and Immutable Types

• Tuples and List types look very similar


• However, there is one major difference: Lists are
mutable
– Contents of a list can be modified
• Tuples and Strings are immutable
– Contents can not be modified

25
Programming
Summary of Sequences
Operation Meaning
seq[i] i-th element of the sequence
len(seq) Length of the sequence
seq1 + seq2 Concatenate the two sequences
num*seq
seq*num Repeat seq num times

seq[start:end] slice starting from start, and ending at end-1


e in seq True if e is present is seq, False otherwise
e not in seq True if e is not present is seq, False otherwise
for e in seq Iterate over all elements in seq (e is bound to one element per
iteration)

Sequence types include String, Tuple and List.


Lists are mutable, Tuple and Strings immutable. 26
Programming
DICTIONARIES

• Python dictionary is an unordered collection of


items. Each item of a dictionary has
a key/value pair.
• Dictionaries are optimized to retrieve values when
the key is known.
Creating Python Dictionary

Creating a dictionary is as simple as placing items inside curly braces {} 


separated by commas.

An item has a key and a corresponding value that is expressed as


a pair (key: value).

While the values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements) and must be
unique.
Accessing Elements from Dictionary

While indexing is used with other data types to access values, a dictionary
uses keys.

Keys can be used either inside square brackets [] or with the get() method.

If we use the square brackets [], KeyError is raised in case a key is not found


in the dictionary.

On the other hand, the get() method returns None if the key is not found.


Method Description

clear() Removes all items


from the dictionary.

copy() Returns a shallow


copy of the dictionary.
Returns a new
dictionary with keys
fromkeys(seq[, v]) from seq and value
equal to v (defaults to
None).
Returns the value of
the key. If the key
get(key[,d]) does not exist, returns
d (defaults to None).
Return a new object
items() of the dictionary's
items in (key, value)
format.
Returns a new object
keys() of the dictionary's
keys.
Removes the
item with the
key and returns
its value or d if
pop(key[,d]) key is not
found. If d is
not provided
and the key is
not found, it
raises KeyError.
Removes and
returns an
arbitrary item
popitem() (key, value).
Raises KeyError
if the dictionary
is empty.
Returns the
corresponding
value if the key
is in the
dictionary. If
setdefault not, inserts the
(key[,d])
key with a
value of d and
returns d
(defaults to
None).
Updates the
dictionary with
the key/value
update([other]) pairs from

You might also like