140 likes | 157 Vues
Python Data Structures. CS 265 Seth Simpson. Lists. Creating Lists exampleList = [1,3,5,7,9] List methods Append( element) – appends element to end Extend( list ) – extends the list with another list Insert( position, element) – insert element at the given position
E N D
Python Data Structures CS 265 Seth Simpson
Lists • Creating Lists • exampleList = [1,3,5,7,9] • List methods • Append(element) – appends element to end • Extend(list) – extends the list with another list • Insert(position, element) – insert element at the given position • Remove(element) – removes the first occurrence of the element
Lists (Cont) • More List methods • Pop(index) – Remove and return the element at index (last element by default) • Index(element) – returns index of the first occurrence of element • Count(element) – returns the number of times element appears in the list • Sort() – sorts the list • Reverse() – reverses the list
Lists as Stacks • Last in – First out • List pop function enables us to treat lists as stacks.
Lists as Queues • First in – first out • Popping end elements of a list is fast because the elements don’t need to be rearranged • Popping from the front of a list is slow because the list needs to be rearranged
List Filtering • Filter(function name, list) • Returns a sequence of items for which function(item) is true. • Example:
List Mapping • Map(function name, list) • Calls the function for each value in the list and outputs the results as list • Example:
List Reducing • Reduce(function name, list) • Returns a single value by computing the function value on the first two elements, then the result of that with the next element and so on.
Sets • Unordered collection with no duplicates
Dictionaries • Unsorted set of Key : Value pairs
Dictionaries (Cont) • Can also call the dict() constructor to create a dictionary. • Printing out Dictionaries