9.1 Tuple

A tuple is a sequence of elements that cannot be modified. It can contain any Python or more values. the items of a tuple are enclosed in parenthesis and separated by commas.

Some tuples: myTuple = (1,2,3 ) t2 = ('H', 'e', 'L') t3 = ('College drive', ['A10','B20','C10'], 98008, 'WA', )

You can see tuple as an immutable list. A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.

Notes:

  • empty tuple: ()
  • tuple with a single item: ('lonely item',) has the unusual notation, a trailing comma.
  • longer tuples don't require a trailing comma, but is allowed, some programmers prefer to always include the trailing comma. (1,2,3,)

Tuple is similar to list in many ways:

  • Just like a list, the elements of a tuple have a defined order. Elements of a tuple is t[0], t[1]...and so on.

  • Negative indices count from the end of the tuple.

  • Slicing works too. Slicing doesn't change the original tuple, it just create a new tuple.

  • Add two tuples together to make a new tuple Repeat a tuple to make new tuple

tuple(a list) will turn a list into a tuple just like list(a tuple) will turn a tuple into a list

tuple(a string) will return a tuple with the letter elements from a string

Ex. 9.1-1 tuple basics

>>> t = ('math', 101, 'grade', 98, )
>>> t[0]
math
>>> t[1]
101
>>> t[-1]
98
>>> new = t[2:]
>>> new
grade 98
>>> t           # check the original t unchanged
('math', 101, 'grade', 98, )
>>>
>>> t2 = ('letter grade', 'A',)
>>> t3 = t + t2
>>> t3
('math', 101, 'grade', 98, 'letter grade', 'A', )
>>>
>>> t4 = ('Hello',) *3
>>> t4
('Hello', 'Hello', 'Hello',)
>>>
>>> lst = ['good', 'morning']
>>> myTuple = tuple(lst)      # turn a list into a tuple
>>> myTuple
('good', 'morning')
>>> t5 = tuple('bear')     # turn a string into a tuple
>>> t5
('b', 'e', 'a', 'r')
>>>

Tuple's difference than list is mostly about it's immutability. Tuple can not be changed once it's created.

Lists have many methods that can modify them like adding or remove elements using append(), insert(), pop(), and extend(); or just change values by assigning new values to elements using index, such as lst[0]=newValue.

Tuples have no methods that would allow you to change them. We can not add or remove items from a tuple or to change them.

But we can check some information on a tuple:

Check the length of a tuple; Check if an element exists in the tuple, find out the index of a particular value and also count the frequency a value appears in a tuple, all these doesn’t change the tuple.

Ex. 9.1-2 check on tuple

>>> t = ('red','green','blue','yellow','blue','blue',)
>>> len(t)
4
>>> t.index('blue')        # returns the first time the item appears
2
>>> t.count('blue')
3
>>> 'yellow' in t           # check membership
True
>>>
>>> t[3]
'yellow'
>>> t[2] = 'pink'       # see if we can change element's value?
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
>>>t.append('white')     # see if we can add a new element
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>>

So what are tuples good for?

They are useful to group elements of different type together. t = ('bananas','200g',0.55)

It's safer than a list. Since it's impossible to accidentally change a tuple, it's good for something that you don't want anyone to change like school records.

Tuples are faster to process than lists.

In contrast to lists, tuples can also be used as keys in dictionaries. Dictionary keys can be any immutable type, so tuple fits the role and list doesn't.

But if a tuple's elements are lists, that makes the tuple mutable, then that tuple is not safe as dictionary key. So only tuples of immutable types(such as strings, numbers) can be dictionary keys.

Keep in mind: Lists and tuples are great when you want data to be ordered.

When you don't care the order of data, dictionaries and sets come into the picture.

9.2 Sets

Sets are another type of data structure, sets are unordered unique objects enclosed in Curly braces {}. Python set is similar to a dictionary that only has keys and no corresponding values. Sets are very handy to quickly remove duplicates.

mySet = {1,2,'h',5,6}

Notes on Set:

  • An empty set is set( ), not { }; the latter is for an empty dictionary.

  • No duplicate items in a set.

  • Curly braces or the set() function can be used to create sets. Duplicate items will be removed automatically.

Ex. 9.2-1 set basics

>>> mySet = {1,2,3,4,5,5,5,6,7,8}
>>> len(mySet)
8               # why not 10??
>>> mySet       # duplicate will be removed
{1,2,3,4,5,6,7,8}
>>> 
>>> lst = [8,9,6,7,6,8]
>>> s2 = set(lst)    # create a set from a list
>>> s2
{6,8,9,7}           # no duplicate, no order
>>>
>>> m = set('hello')    # turns a string into a set of unique letters
>>> print(m)
{'o', 'h', 'l', 'e'}
>>>
>>> s0 = set()      # call set() function with no argument will return an empty set
>>> s0
set()         # a set with no items, empty set is not {}
>>>

Some methods that works on sets:

Add items to an existing set: add(aItem) and update(anotherSet) methods.

Remove items from a set: remove(aItem) pop() will remove a random item from the set and return it's value. clear() methods will remove all items from a set.

Ex. 9.2-2 set methods

>>> farm = {'chicken', 'duck'}
>>> farm.add('goose')         # add one item at a time
>>> farm
{'chicken', 'goose', 'duck'}
>>>
>>> farm.update({'cow', 'sheep', 'chicken', 'elephant'})    
>>> farm
{'chicken', 'goose', 'cow', 'elephant', 'duck','sheep' }
>>> 'elephant' in farm   # fast membership testing
True
>>>
>>> farm.remove('elephant')
{'chicken', 'duck', 'goose', 'cow', 'sheep' }
>>>
>>> farm.pop()     # remove a random item and return it's value
'duck'
>>> farm
{'chicken', 'goose', 'cow', 'sheep' }
>>>
>>> farm.clear()    
>>> farm
set()        # All gone! The farm is quiet now.
>>>

Make a copy: copy() methods will return a copy of the original set as a new set. This is different than just assigning value.

Ex. 9.2-3 set copy

>>> records = {'Math', 98, 'A+', 'Science', 90, 'A'}
>>> rec_copy1 = records
>>> rec_copy2 = records.copy()
>>>
>>> records.clear()
>>>
>>> records
set()
>>> rec_copy1   # rec_copy1 and records refer to the same object
set()
>>> rec_copy2
{'Math', 98, 'A+', 'Science', 90, 'A'}    # Thank God! We have a backup copy!
>>>

Some useful set operations:

Ex. 9.2-4 set operations

>>> s = {'H', 'I', 'J', 'K', 1,2,3}
>>> t = { 'o', 'p', 'e', 'n', 1,2,3}
>>>
>>> s - t         # in s but not in t
{'H', 'I', 'J', 'K'}
>>> s.difference(t)
{'H', 'I', 'J', 'K'}

>>> s & t         # in both s and t
{1, 2, 3}
>>> s.intersection(t)
{1, 2, 3}

>>> s | t        # all unique items from both s and t
{'H', 'I', 'J', 'K',1,2,3, 'p', 'e', 'n','o'}
>>> s.union(t)
{'H', 'I', 'J', 'K', 'o', 'p', 'e', 'n',1,2,3}

Similarly to list comprehensions, we can use set comprehensions to create a set:

Ex. 9.2-5 set comprehension

>>>
>>> a = {x for x in 'abcdefg' if x not in 'abc'}
>>> a
{'g', 'd', 'e', 'f'}

results matching ""

    No results matching ""