0% found this document useful (0 votes)
41 views

Unit3 2

Python lists allow us to store multiple values in a single variable. Lists are mutable, ordered sequences of elements that can contain any type of Python object. We can access elements using indexes, slice lists, modify them by adding/removing elements, and use built-in functions like len(), max(), min() on lists. Dictionaries are another powerful Python data type that store mappings of unique keys to values. Unlike lists, dictionaries are not ordered and allow for fast lookup of values using keys of any immutable type.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Unit3 2

Python lists allow us to store multiple values in a single variable. Lists are mutable, ordered sequences of elements that can contain any type of Python object. We can access elements using indexes, slice lists, modify them by adding/removing elements, and use built-in functions like len(), max(), min() on lists. Dictionaries are another powerful Python data type that store mappings of unique keys to values. Unlike lists, dictionaries are not ordered and allow for fast lookup of values using keys of any immutable type.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Python Lists

A List is a kind of Collection


• A collection allows us to put many values in a single “variable”
• A collection is nice because we can carry all many values around in
one convenient package.
• In a string, the values are characters; in a list, they can be any type.
The values in a list are called elements or sometimes items.

friends = [ 'Joseph', 'Glenn', 'Sally' ]

carryon = [ 'socks', 'shirt', 'perfume' ]


List Constants
• List constants are surrounded by >>> print ([1, 24, 76])
square brakets and the [1, 24, 76]
elements in the list are >>> print (['red', 'yellow', 'blue’])
separated by commas. ['red', 'yellow', 'blue']
• A list element can be any >>> print (['red', 24, 98.6])
Python object - even another ['red', 24, 98.599999999999994]
list >>> print ([ 1, [5, 6], 7])
• A list can be empty [1, [5, 6], 7]
>>> print ([])
[]
We already use lists!

5
4
for i in [5, 4, 3, 2, 1] :
3
print ( i )
2
print ('Blastoff!’)
1
Blastoff!
Lists and definite loops - best pals

friends = ['Joseph', 'Glenn', 'Sally']


for friend in friends :
print ('Happy New Year:', friend) Happy New Year: Joseph
print ('Done!’) Happy New Year: Glenn
Happy New Year: SallyDone!
Looking Inside Lists
• Just like strings, we can get at any single element in a list using an
index specified in square brackets

>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]


Joseph Glenn Sally >>> print (friends[1])
Glenn
0 1 2 >>>
Lists are Mutable >>> fruit = 'Banana’
>>> fruit[0] = 'b’
Traceback
• Strings are "immutable" - TypeError: 'str' object does not
we cannot change the support item assignment
contents of a string - we >>> x = fruit.lower()
must make a new string to >>> print (x)
make any change banana
• Lists are "mutable" - we can >>> lotto = [2, 14, 26, 41, 63]
change an element of a list >>> print (lotto)
using the index operator >>>[2, 14, 26, 41, 63]
>>> lotto[2] = 28
>>> print (lotto)
>>>[2, 14, 28, 41, 63]
How Long is a List?
• The len() function takes a list as
a parameter and returns the >>> greet = 'Hello Bob’
number of elements in the list >>> print (len(greet))
• Actually len() tells us the 9
number of elements of any set >>> x = [ 1, 2, 'joe', 99]
or sequence (i.e. such as a >>> print (len(x))
string...) 4
>>>
Concatenating lists using +
• We can create a new list by
adding two exsiting lists together
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print (c)
[1, 2, 3, 4, 5, 6]
>>> print (a)
[1, 2, 3]
Use of * operator
❑The first example repeats [0]
• The * operator repeats a list a four times.
given number of times ❑The second example repeats
• >>> [0] * 4 the list [1, 2, 3] three times.
• [0, 0, 0, 0]
• >>> [1, 2, 3] * 3
• [1, 2, 3, 1, 2, 3, 1, 2, 3] ❑What if we will multiply by 0
or 1.2???????
Lists can be sliced using :

>>> t = [9, 41, 12, 3, 74, 15]


>>> t[1:3]
[41,12] Remember: Just like in
>>> t[:4] strings, the second
[9, 41, 12, 3] number is "up to but not
>>> t[3:] including"
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]
List Methods

>>> x = list()
>>> print (type(x))
>>> <type 'list'>
>>> print(dir(x))
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort’…etc]
>>>
Building a list from scratch
• We can create an empty
list and then add >>> stuff = list()
elements using the >>> stuff.append('book')
append method >>> stuff.append(99)
• The list stays in order and >>> print (stuff)
new elements are added ['book', 99]
at the end of the list >>> stuff.append('cookie')
>>> print (stuff)
['book', 99, 'cookie']
Using extend on list

• >>> t1 = ['a', 'b', 'c']


• >>> t2 = ['d', 'e']
• >>> t1.extend(t2)
• >>> t1
• ['a', 'b', 'c', 'd', 'e']
• This example leaves t2 unmodified.
Is Something in a List?
• Python provides two
operators that let you >>> some = [1, 9, 21, 10, 16]
check if an item is in a >>> 9 in some
list True
• These are logical >>> 15 in some
operators that return False
True or False >>> 20 not in some
• They do not modify the True
list >>>
A List is an Ordered Sequence

• A list can hold many items


and keeps those items in the >>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
order until we do something >>> friends.sort()
to change the order >>> print (friends)
• A list can be sorted (i.e. ['Glenn', 'Joseph', 'Sally']
change its order) >>> print (friends[1])
• The sort method (unlike in Joseph
strings) means "sort yourself" >>>
Built in Functions and Lists
• There are a number of >>> nums = [3, 41, 12, 9, 74, 15]
functions built into >>> print (len(nums)))
Python that take lists as 6
parameters >>> print (max(nums))
• Remember the loops we 74
built? These are much >>> print (min(nums))
simpler 3
>>> print (sum(nums))
154
>>> print (sum(nums)/len(nums))
25
Best Friends: Strings and Lists

>>> abc = 'With three words’ >>> print (stuff)


>>> stuff = abc.split() ['With', 'three', 'words']
>>> print (stuff) >>> for w in stuff :
['With', 'three', 'words'] ... print (w)
>>> print (len(stuff)) ...
3 With
>>> print (stuff[0]) Three
With Words
>>>

Split breaks a string into parts produces a list of strings. We think of these as
words. We can access a particular word or loop through all the words.
Deleting elements
There are several ways to delete elements from a list. If you know the index of the element
you want, you can use pop:

Pop modifies the list and returns the element that was removed. If you don’t provide an
index, it deletes and returns the last element.
Deleting elements
If you don’t need the removed value, you can use the del operator:

If you know the element you want to remove (but not the index), you can
use remove:

To remove more than one element, you can use del with a slice index:
Aliasing
If a refers to an object and you assign b = a, then both variables refer to the same object:

The association of a variable with an object is called a reference. In this example, there
are two references to the same object.

An object with more than one reference has more than one name, so we say that the
object is aliased.
A Story of Two Collections..
• List
• A linear collection of values that stay in order

• Dictionary
• A “bag” of values, each with its own label
Dictionaries
tissue
calculator

perfume
money
candy
Dictionaries
• Dictionaries are Python’s most powerful data collection
• Dictionaries allow us to do fast database-like operations in Python
• Dictionaries have different names in different languages
• Associative Arrays - Perl / Php
• Properties or Map or HashMap - Java
• Property Bag - C# / .Net
Dictionaries
• A dictionary is like a list, but more general. In a list, the indices have
to be integers; in a dictionary they can be (almost) any type.
• A dictionary contains a collection of indices, which are called keys,
and a collection of values.
• Each key is associated with a single value. The association of a key and
a value is called a key-value pair or sometimes an item.
• In mathematical language, a dictionary represents a mapping from
keys to values, so you can also say that each key “maps to” a value.
• As an example, we’ll build a dictionary that maps from English to
Spanish words, so the keys and the values are all strings.
Dictionaries
• The function dict creates a new dictionary with no items. Because dict
is the name of a built-in function, you should avoid using it as a
variable name.
• >>> eng2sp = dict()
• >>> eng2sp
• {}
• The squiggly-brackets, {}, represent an empty dictionary.
• To add items to the dictionary, you can use square brackets:
• >>> eng2sp['one'] = 'uno'
• This line creates an item that maps from the key 'one' to the value
'uno'
Dictionaries
• If we print the dictionary again, we see a key-value pair with a colon
between the key and value:
• >>> eng2sp
• {'one': 'uno'}
• This output format is also an input format.
• you can create a new dictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres’}
• But if you print eng2sp, you might be surprised:
• >>> eng2sp
• {'one': 'uno', 'three': 'tres', 'two': 'dos'}
• The order of the key-value pairs might not be the same.
Dictionaries
• Lists index their entries >>> purse = dict()
based on the position in >>> purse['money'] = 12
the list >>> purse['candy'] = 3
• Dictionaries are like bags - >>> purse['tissues'] = 75
no order >>> print purse
{'money': 12, 'tissues': 75, 'candy': 3}
• So we index the things we
put in the dictionary with >>> print (purse['candy’])
a “lookup tag” 3
>>> purse['candy'] = purse['candy'] + 2
>>> print purse
{'money': 12, 'tissues': 75, 'candy': 5}
Comparing Lists and Dictionaries
• Dictionaries are like Lists except that they use keys instead of
numbers to look up values

>>> ddd = dict()


>>> lst = list() >>> ddd['age'] = 21
>>> lst.append(21) >>> ddd['course'] = 182
>>> lst.append(183) >>> print ddd
>>> print lst[21, 183] {'course': 182, 'age': 21}
>>> lst[0] = 23 >>> ddd['age'] = 23
>>> print lst[23, 183] >>> print ddd
{'course': 182, 'age': 23}
>>> lst = list()
>>> lst.append(21) List
>>> lst.append(183) Key Value
>>> print lst
[21, 183] [0] 21
lll
>>> lst[0] = 23 [1] 183
>>> print lst
[23, 183]

>>> ddd = dict()


>>> ddd['age'] = 21 Dictionary
>>> ddd['course'] = 182 Key Value
>>> print ddd
{'course': 182, 'age': 21} ['course'] 183
>>> ddd['age'] = 23
ddd
['age'] 21
>>> print ddd
{'course': 182, 'age': 23}
Dictionaries
• If the key isn’t in the dictionary, you get an exception:
• >>> eng2sp['four']
• KeyError: 'four’
• The len function works on dictionaries; it returns the number of key-value
pairs:
• >>> len(eng2sp)
• 3
• The in operator works on dictionaries, too; it tells you whether something
appears as a key
• in the dictionary (appearing as a value is not good enough).
• >>> 'one' in eng2sp
• True
• >>> 'uno' in eng2sp
• False
Dictionaries
• To see whether something appears as a value in a dictionary, you can
use the method
• values, which returns a collection of values, and then use the in
operator:
• >>> vals = eng2sp.values()
• >>> 'uno' in vals
• True
Search time in List and Dictionaries
• The in operator uses different algorithms for lists and
dictionaries. For lists, it searches the elements of the list in
order. As the list gets longer, the search time gets longer in
direct proportion.
• Python dictionaries use a data structure called a hashtable
that has a remarkable property: the in operator takes about
the same amount of time no matter how many items are in
the dictionary.
Dictionary Literals (Constants)
• Dictionary literals use curly braces and have a list of key : value
pairs
• You can make an empty dictionary using empty curly braces

>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}


>>> print jjj
{'jan': 100, 'chuck': 1, 'fred': 42}
>>> ooo = { }>>> print ooo{}
>>>
Most Common Name?

zhen zhen marquard cwen


zhen csev
csev
marquard marquard
csev cwen
zhen
zhen
Most Common Name?
Most Common Name?

zhen zhen marquard cwen


zhen csev
csev
marquard marquard
csev cwen
zhen zhen
Many Counters with a Dictionary
• One common use of dictionary is
counting how often we “see” Key Value
something
>>> ccc = dict()
>>> ccc['csev'] = 1
>>> ccc['cwen'] = 1
>>> print ccc
{'csev': 1, 'cwen': 1}
>>> ccc['cwen'] = ccc['cwen'] + 1
>>> print ccc
{'csev': 1, 'cwen': 2}
Dictionary Tracebacks
• It is an error to reference a key which is not in the dictionary
• We can use the in operator to see if a key is in the dictionary

>>> ccc = dict()


>>> print ccc['csev']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'csev'
>>> print 'csev' in ccc
False
When we see a new name
• When we encounter a new name, we need to add a new entry in the
dictionary and if this the second or later time we have seen the name,
we simply add one to the count in the dictionary under that name

counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
if name not in counts:
counts[name] = 1
else :
counts[name] = counts[name] + 1
print counts

{'csev': 2, 'zqian': 1, 'cwen': 2}


Looping and dictionaries
• If you use a dictionary in a for statement, it traverses the keys of the
dictionary. For example, print_hist prints each key and the
corresponding value:
Looping and dictionaries
• Again, the keys are in no particular order. To traverse the keys in sorted
order, you can use the built-in function sorted:
Looping and dictionaries
• Again, the keys are in no particular order. To traverse the keys in sorted
order, you can use the built-in function sorted:
Tuples
Tuples are like lists
• Tuples are another kind of sequence that function much like a list -
they have elements which are indexed starting at 0

>>> x = ('Glenn', 'Sally', 'Joseph')


>>> print (x[2]) >>> for iter in y:
>>Joseph ... print (iter)
>>> y = ( 1, 9, 2 ) ...
>>> print y 1
(1, 9, 2) 9
>>> print max(y) 2
9 >>>
..but.. Tuples are "immutable"
• Unlike a list, once you create a tuple, you cannot alter its contents -
similar to a string

>>> y = 'ABC’ >>> z = (5, 4, 3)


>>> x = [9, 8, 7] >>> y[2] = 'D’ >>> z[2] = 0
>>> x[2] = 6 Traceback:'str' Traceback:'tuple'
>>> print x[9, 8, 6] object does object does
>>> not support item not support item
Assignment Assignment
>>> >>>
Tuples
• Syntactically, a tuple is a comma-separated list of values:
• >>> t = 'a', 'b', 'c', 'd', 'e'
• Although it is not necessary, it is common to enclose tuples in parentheses:
• >>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
>>> type(t1)
<class 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<class 'str'>
Tuples
• Another way to create a tuple is the built-in function tuple. With no argument, it
creates
• an empty tuple:
• >>> t = tuple()
• >>> t
• ()
If the argument is a sequence (string, list or tuple), the result is a tuple
with the elements of
the sequence:
>>> t = tuple('lupins')
>>> t
('l', 'u', 'p', 'i', 'n', 's')
Tuples
• Most list operators also work on tuples. The bracket operator indexes an element:
• >>> t = ('a', 'b', 'c', 'd', 'e')
• >>> t[0]
• 'a'
• And the slice operator selects a range of elements.
• >>> t[1:3]
• ('b', 'c')
• But if you try to modify one of the elements of the tuple, you get an error:
• >>> t[0] = 'A'
• TypeError: object doesn't support item assignment
• Because tuples are immutable
Tuples
• Most list operators also work on tuples. The bracket operator indexes an element:
• >>> t = ('a', 'b', 'c', 'd', 'e')
• >>> t[0]
• 'a'
• And the slice operator selects a range of elements.
• >>> t[1:3]
• ('b', 'c')
• But if you try to modify one of the elements of the tuple, you get an error:
• >>> t[0] = 'A'
• TypeError: object doesn't support item assignment
• Because tuples are immutable
Tuple assignment
• It is often useful to swap the values of two variables. With conventional
assignments, you have to use a temporary variable. For example, to
swap a and b:
• >>> temp = a
• >>> a = b
• >>> b = temp
• This solution is cumbersome; tuple assignment is more elegant:
• >>> a, b = b, a
• The left side is a tuple of variables; the right side is a tuple of
expressions. Each value is assigned to its respective variable. All the
expressions on the right side are evaluated before any of the
assignments.
Tuple assignment
• The number of variables on the left and the number of values on the
right have to be the same:
• >>> a, b = 1, 2, 3
• ValueError: too many values to unpack
• More generally, the right side can be any kind of sequence (string, list or
tuple). For example, to split an email address into a user name and a
domain, you could write:
• >>> addr = '[email protected]'
• >>> uname, domain = addr.split('@')
• The return value from split is a list with two elements; the first element
is assigned to uname, the second to domain.
Tuples as return values
• The built-in function divmod takes two arguments and returns a tuple of
two values, the quotient and remainder. You can store the result as a
tuple:
• >>> t = divmod(7, 3)
• >>> t
• (2, 1)
• Or use tuple assignment to store the elements separately:
• >>> quot, rem = divmod(7, 3)
• >>> quot
• 2
• >>> rem
• 1
Lists and tuples
• zip is a built-in function that takes two or more sequences and
interleaves them.
• This example zips a string and a list:
• >>> s = 'abc'
• >>> t = [0, 1, 2]
• >>> zip(s, t)
• <zip object at 0x7f7d0a9e7c48>
• The result is a zip object that knows how to iterate through the pairs.
Lists and tuples
• for pair in zip(s, t):
• ... print(pair)
• ...
• ('a', 0)
• ('b', 1)
• ('c', 2)
• A zip object is a kind of iterator, which is any object that iterates through
a sequence.
• Iterators are similar to lists in some ways, but unlike lists, you can’t use
an index to select an element from an iterator.
Lists and tuples
• If you want to use list operators and methods, you can use a zip object to
make a list:
• >>> list(zip(s, t))
• [('a', 0), ('b', 1), ('c', 2)]
• The result is a list of tuples.
• If the sequences are not the same length, the result has the length of the
shorter one.
• >>> list(zip('Anne', 'Elk'))
• [('A', 'E'), ('n', 'l'), ('n', 'k')]
Things not to do with tuples
>>> x = (3, 2, 1)
>>> x.sort()
Traceback:AttributeError: 'tuple' object has no
attribute 'sort’
>>> x.append(5)
Traceback:AttributeError: 'tuple' object has no
attribute 'append’
>>> x.reverse()
Traceback:AttributeError: 'tuple' object has no
attribute 'reverse’
>>>
A Tale of Two Sequences

>>> l = list()
>>> dir(l)[
'append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']

>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples are more efficient
• Since Python does not have to build tuple structures to be
modifiable, they are simpler and more efficient in terms of memory
use and performance than lists.

• So in our program when we are making "temporary variables" we


prefer tuples over lists.
Tuples and Assignment
• We can also put a tuple on the left hand side of an assignment
statement
• We can even omit the parenthesis

>>> (x, y) = (4, 'fred')


>>> print (y)
Fred
>>> (a, b) = (99, 98)
>>> print (a)
99
Tuples and
Dictionaries
>>> d = dict()
>>> d['csev'] = 2
• The items() method in >>> d['cwen'] = 4
dictionaries returns a >>> for (k,v) in d.items():
list of (key, value) ... print (k, v)
tuples ...
csev 2
cwen 4
>>> tups = d.items()
>>> print (tups)
[('csev', 2), ('cwen', 4)]
Dictionaries and tuples
• Dictionaries have a method called items that returns a sequence of
tuples, where each
• tuple is a key-value pair.
• >>> d = {'a':0, 'b':1, 'c':2}
• >>> t = d.items()
• >>> t
• dict_items([('c', 2), ('a', 0), ('b', 1)])
Dictionaries and tuples
• Going in the other direction, you can use a list of tuples to initialize a
new dictionary:
• >>> t = [('a', 0), ('c', 2), ('b', 1)]
• >>> d = dict(t)
• >>> d
• {'a': 0, 'c': 2, 'b': 1}
Sets
• Indentified by curly braces
• {'Alice', 'Bob', 'Carol'}
• {'Dean'} is a singleton
• Can only contain unique elements
• Duplicates are eliminated
• Immutable like tuples and strings
Sets do not contain duplicates
• >>> cset = {11, 11, 22}
• >>> cset
{11, 22}
Sets are immutable
• >>> aset = {11, 22, 33}
• >>> bset = aset Union of two
sets
• >>> aset = aset | {55}
• >>> aset
{33, 11, 22, 55}
• >>> bset
{33, 11, 22}
Sets have no order
• >>> {1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
• >>> {11, 22, 33}
{33, 11, 22}
Sets do not support indexing

• >>> myset = {'Apples', 'Bananas', 'Oranges'}


• >>> myset
{'Bananas', 'Oranges', 'Apples'}
• >>> myset[0]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
myset[0]
TypeError: 'set' object does not support indexing
Examples
• >>> alist = [11, 22, 33, 22, 44]
• >>> aset = set(alist)
• >>> aset
{33, 11, 44, 22}
• >>> aset = aset + {55}
SyntaxError: invalid syntax
Boolean operations on sets (I)

• Union of two sets

A B

• Contains all elements that are in set A or in set B


Boolean operations on sets (II)

• Intersection of two sets

A B

• Contains all elements that are in both sets A and B


Boolean operations on sets (III)
• Difference of two sets

A B

• Contains all elements that are in A but not in B


Boolean operations on sets (IV)
• Symmetric difference of two sets

A B

• Contains all elements that are either


• in set A but not in set B or
• in set B but not in set A
Boolean operations on sets (V)
• >>> aset = {11, 22, 33}
• >>> bset = {12, 23, 33}
• Union of two sets
• >>> aset | bset
{33, 22, 23, 11, 12}
• Intersection of two sets:
• >>> aset & bset
{33}
Boolean operations on sets (VI)
• >>> aset = {11, 22, 33}
• >>> bset = {12, 23, 33}
• Difference:
• >>> aset – bset
{11, 22}
• Symmetric difference:
• >>> aset ^ bset
{11, 12, 22, 23}

You might also like