Tuesday, November 20, 2012

Part 5 - Python Data structures

In Part 5, we will review Python's data structures.



Python Data Structures

Often time, you need to save the data in a list or an array, so you can access it later in a orderly manner (through the use of an index of a list) or by mapping a certain value to a specific key, so you can later look it up (like a dictionary). Or if you need a way to save a constant value that doesn't get changed(tuple) or a sequence of unique values (set) that you can do Boolean operation on. Python offers all these different data structure for you to accomplish these tasks.

  • Lists [ ]
  • Tuple ( )
  • Dictionary { key : value}
  • Sets

Lists

          List is a sequence of items separated by comma between square brackets [ ]
o   A = [1, 2, 3, 4, 5]
o   B = [‘Adam’, ‘Bob’, ‘Cindy’]
o   C = [ 1, 2, 3, ‘A’, ‘B’, ‘C’]

  • Items in a list do not need to have the same type
  • Lists are indexed starting with 0.
  • List items can be updated, deleted
  • List items can be added or appended
  • You can count a list, show min and max value
  • You can reverse a list, sort a list
  • You can join two list using extend 


Tuple

          Tuples are like lists except they are immutable.


  •  Tuple items cannot be updated or deleted.
  •  Tuple items are not indexed.
  •  You can use “in” to verify item membership in a tuple
  •  Tuple can be nested.
  •  Empty tuple  t= ( )
  •  Tuple with 1 item  t = (1,)
  •  Tuple with 3 items using parenthesis t = (“A”, “B”, 666)
  •  Tuple without using parenthesis ( )  t = “A”, “B”, 666

Dictionary

          A Dictionary is an unordered set of key: value pairs, with the requirement that the keys are unique.


  • tel= {‘john': 1234, ‘Mary’: 5678}
  • tel.keys( ) returns the keys in a list [ key1, key2, key3]
  •  tel.values( ) returns the values in a list [val1,val2, val3]
  •  tel.items( )  returns the list with pairs of key values.
  •                         [(key1,value1), (key2,value2), (key3,value3)]
  • tel.has_key(‘john’) returns True, if john is in the dictionary
  •  tel[‘john’]=9999 value can be updated
  • del tel[‘john] removes entry john
  •  del tel  removes the whole dictionary tel
  •  tel.clear() removes all items in dictionary tel

Sets

A set is an unordered collection with no duplicate elements. 


  • designers = Set(['John', 'Jane', 'Jack', 'Janice'])  
  • managers = Set(['Jane', 'Jack', 'Susan', 'Zack']
  • mySet = Set([‘A’,’B’, ‘C’])  
  • Use union | to join 2 sets, listing unique items
    • mySet = designers | managers
  • Use intersection & to find common items
    • mySet = designers & managers
  • Use difference - to find the different items between sets
    • mySet = designers – managers
  • mySet.add(x) : add item to the set
  • mySet.update(x) : update
  • mySet.issuperset( x) : check if
  • mySet.discard( x) : discard an item from set










No comments:

Post a Comment