Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Python 3

The document discusses various Python data structures including lists, tuples, sets and dictionaries. It provides details on how to manipulate and use lists as stacks and queues. It also covers functional programming tools like filter(), map() and reduce(). List comprehensions and the del statement are explained. Tuples can be nested and support packing and unpacking of values.

Uploaded by

CraVien
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python 3

The document discusses various Python data structures including lists, tuples, sets and dictionaries. It provides details on how to manipulate and use lists as stacks and queues. It also covers functional programming tools like filter(), map() and reduce(). List comprehensions and the del statement are explained. Tuples can be nested and support packing and unpacking of values.

Uploaded by

CraVien
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

DATA STRUCTURES

Trianz Confidential
AGENDA
 Compound Data Types
 List
 Manipulation of List
 Using Lists as Stack
 Using Lists as Queue

 Functional Programming Tools – filter(), map() and reduce()


 List Comprehensions
 The del Statement
 Tuples
 Nested Tuples
 Tuples Packing

 Sets
 Membership Test
 Set Operations
 Dictionaries – Manipulation & Functions
Trianz Confidential 2
Lists
 Python has a number of compound data types, used to group
together other values. The most versatile is the list, which can be
written as a list of comma-separated values (items) between square
brackets.
 List items need not all have the same type.
>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]

Trianz Confidential 3
Lists (Contd….)
 Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.

>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs',
100, 'Boo!']

Trianz Confidential 4
Lists (Contd….)
 Unlike strings, which are immutable, it is possible to change
individual elements of a list.
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]

Trianz Confidential 5
Lists (Contd….)
 Assignment to slices is also possible, and this can even change the size of
the list.
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy',
1234]

Trianz Confidential 6
Lists (Contd….)
 The built-in function len() also applies to lists .
>>> len(a)
8

 It is possible to nest lists (create lists containing other lists).


>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra')
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']

Trianz Confidential 7
Using Lists As Stacks
 The list methods make it very easy to use a list as a stack, where the
last element added is the first element retrieved (``last-in, first-out'').
 To add an item to the top of the stack, use append().
 To retrieve an item from the top of the stack, use pop() without an
explicit index.
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>>

Trianz Confidential 8
Using Lists As Queues
 You can also use a list conveniently as a queue, where the first
element added is the first element retrieved (``first-in, first-
out'').
 To add an item to the back of the queue, use append().
 To retrieve an item from the front of the queue, use pop()
with 0 as the index
>>> queue = ["Eric", "John", "Michael"]
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.pop(0)
'Eric'
>>>

Trianz Confidential 9
Functional Programming Tools
 There are three built-in functions that are very useful when used
with lists: filter(), map(), and reduce().
 "filter(function, sequence)" returns a sequence consisting of those
items from the sequence for hich
 function(item) is true.
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]

Trianz Confidential 10
Functional Programming Tool : map
 "map(function, sequence)" calls function(item) for each of the
sequence's items and returns a list of the return values.
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
 More than one sequence may be passed; the function must then
have as many arguments as there are sequences and is called with
the corresponding item from each sequence (or None if some
sequence is shorter than another).
>>> seq = range(8)
>>> def add(x, y): return x+y
...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]

Trianz Confidential 11
Functional Programming Tool : reduce
 "reduce(function, sequence)" returns a single value constructed by
calling the binary function function on the first two items of the
sequence, then on the result and the next item, and so on.
 For example, to compute the sum of the numbers 1 through 10.
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
 If there's only one item in the sequence, its value is returned; if the
sequence is empty, an exception is raised.

Trianz Confidential 12
List Comprehensions
 List comprehensions provide a concise way to create lists without
resorting to use of map(), filter() and/or lambda.
 The resulting list definition tends often to be clearer than lists built
using those constructs.
 Each list comprehension consists of an expression followed by a for
clause, then zero or more for or if clauses.
 The result will be a list resulting from evaluating the expression in
the context of the for and if clauses which follow it.

Trianz Confidential 13
List Comprehensions :Example
 Example:
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]

Trianz Confidential 14
List Comprehensions : Example (contd…)
Example:

>>> vec1 = [2, 4, 6]


>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]

Trianz Confidential 15
List Comprehensions : Example (contd…)
 List comprehensions are much more flexible than
 map() and can be applied to complex expressions and nested
functions.
>>> [str(round(355/113.0, i)) for i in range(1,6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
 If the expression would evaluate to a tuple, it must be parenthesized

Trianz Confidential 16
The del Statement
 There is a way to remove an item from a list given its index
instead of its value: the del statement.
 Unlike the pop()) method which returns a value, the del
keyword is a statement and can also be used to remove slices
from a list (which we did earlier by assignment of an empty list
to the slice).
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a # To delete entire variable
... # Referencing the name a hereafter is an error

Trianz Confidential 17
Tuples
 We saw that lists and strings have many common properties,
such as indexing and slicing operations.
 Since Python is an evolving language, other sequence data
types may be added. There is also another standard sequence
data type: the tuple.
 A tuple consists of a number of values separated by commas.
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')

Trianz Confidential 18
Nested Tuples
 Tuples may be nested.
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
 Tuples are always enclosed in parentheses, so that nested tuples are
interpreted correctly; they may be input with or without surrounding
parentheses.

Trianz Confidential 19
More About Tuples
 Tuples, like strings, are immutable: it is not possible to assign to the
individual items of a tuple.
 A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these.
 Empty tuples are constructed by an empty pair of parentheses; a
tuple with one item is constructed by following a value with a
comma (it is not sufficient to enclose a single value in parentheses).
Ugly, but effective.
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma

Trianz Confidential 20
Tuple Packing
 The statement t = 12345, 54321, 'hello!' is an example of tuple
packing: the values 12345, 54321 and 'hello!‘ are packed together in
a tuple.
 The reverse operation is also possible .
>>> t = 12345, 54321, 'hello!'
>>> x, y, z = t
 This is called, appropriately enough, sequence unpacking.
 Sequence unpacking requires the list of variables on the left to have
the same number of elements as the length of the sequence.
 There is a small bit of asymmetry here:
 packing multiple values always creates a tuple, and
 unpacking works for any sequence.

Trianz Confidential 21
Sets
 Python also includes a data type for sets.
 A set is an unordered collection with no duplicate elements.
 Basic uses include membership testing and eliminating duplicate
entries.
 Set objects also support mathematical operations like union,
intersection, difference, and symmetric difference.
>>> basket=['apple','orange','apple','pear','orange','banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])

Trianz Confidential 22
Sets Memebership Test
 Membership test on sets is performed as follows:
>>> basket=['apple','orange','apple','pear','orange','banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit # membership testing
True
>>> 'grapes' in fruit
False

Trianz Confidential 23
Set Operations
 Membership test on sets is performed as follows:
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

Trianz Confidential 24
Dictionaries
 Dictionaries are sometimes found in other languages as ``associative
memories'' or ``associative arrays''.
 Unlike sequences, which are indexed by a range of numbers,
dictionaries are indexed by keys, which can be any immutable type;
strings and numbers can always be keys.
 Tuples can be used as keys. However, you can't use lists as keys.
 It is best to think of a dictionary as an unordered set of key: value
pairs, with the requirement that the keys are unique (within one
dictionary).
 A pair of braces creates an empty dictionary: { }.
 Placing a comma-separated list of key:value pairs within the braces
adds initial key:value pairs to the dictionary; this is also the way
dictionaries are written on output.
 It is also possible to delete a key:value pair with del.
Trianz Confidential 25
Dictionary Functions
 The keys() method of a dictionary object returns a list of all the keys
used in the dictionary, in arbitrary order
 If you want it sorted, just apply the sort() method to the list of keys.
 To check whether a single key is in the dictionary, either use the
dictionary's has_key() method or the in keyword (i.e. membership
test).

Trianz Confidential 26
Dictionary Functions - Examples
 Examples:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
True
>>> 'guido' in tel
True
Trianz Confidential 27
The dict() Constructor
 The dict() constructor builds dictionaries directly from lists of key-
value pairs stored as tuples.
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
...
>>> dict([(x, x**2) for x in (2, 4, 6)]) # list comprehension
{2: 4, 4: 16, 6: 36}
 When the keys are simple strings, it is sometimes easier to specify
pairs using keyword arguments.
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

Trianz Confidential 28
Thank you

Trianz Confidential 29

You might also like