GF Python Data Structures
GF Python Data Structures
By Greg Felber
Lists
• An ordered group of items
• Does not need to be the same type
– Could put numbers, strings or donkeys in the
same list
• List notation
– A = [1,”This is a list”, c, Donkey(“kong”)]
Methods of Lists
• List.append(x)
– adds an item to the end of the list
• List.extend(L)
– Extend the list by appending all in the given list L
• List.insert(I,x)
– Inserts an item at index I
• List.remove(x)
– Removes the first item from the list whose value is
x
Examples of other methods
• a = [66.25, 333, 333, 1, 1234.5] //Defines List
– print a.count(333), a.count(66.25), a.count('x') //calls method
– 2 1 0 //output
• a.index(333)
– //Returns the first index where the given value appears
– 1 //ouput
• a.reverse() //Reverses order of list
– a //Prints list a
– [333, 1234.5, 1, 333, -1, 66.25] //Ouput
• a.sort()
– a //Prints list a
– [-1, 1, 66.25, 333, 333, 1234.5] //Output
Using Lists as Stacks
• The last element added is the first element retrieved
• To add an item to the stack,
append() must be used
– stack = [3, 4, 5]
– stack.append(6)
– Stack is now [3, 4, 5, 6]
• To retrieve an item from the top of the stack, pop must
be used
– Stack.pop()
– 6 is output
– Stack is now [3, 4, 5] again
Using Lists as Queues
• First element added is the first element
retrieved
• To do this collections.deque
must be implemented
List Programming Tools
• Filter(function, sequence)
– Returns a sequence consisting of the items from
the sequence for which function(item) is true
– Computes primes up to 25
Map Function
• Map(function, sequence)
– Calls function(item) for each of the sequence’s
items