17
Data Structures in Data Structures in Python Python By: Christopher Todd By: Christopher Todd

Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Embed Size (px)

Citation preview

Page 1: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Data Structures in PythonData Structures in Python

By: Christopher ToddBy: Christopher Todd

Page 2: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Lists in PythonLists in Python

A list is a group of comma-separated A list is a group of comma-separated values between square brackets. values between square brackets. The values can be of multiple types: such as The values can be of multiple types: such as

strings, ints, or other lists.strings, ints, or other lists.Lists start at the indices 0Lists start at the indices 0Defining a list:Defining a list:

A = [ ‘hello’, 5, ‘test’, 8]A = [ ‘hello’, 5, ‘test’, 8]B = [ 0, 1, ‘test2’, A]B = [ 0, 1, ‘test2’, A]

Page 3: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Methods of a ListMethods of a List len()len()

Gives the size of the listGives the size of the list append()append()

Adds an item to the end of the listAdds an item to the end of the list extend(extend(LL) )

Extend the list by appending all the itemsExtend the list by appending all the items remove(remove(xx) )

Remove the first item from the list whose value is Remove the first item from the list whose value is xx. It . It is an error if there is no such item. is an error if there is no such item.

pop([pop([ii]) ]) Remove the item at the given position in the listRemove the item at the given position in the list

Page 4: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Methods of a ListMethods of a List

index(x)index(x)Return the index of the first item whose value Return the index of the first item whose value

is equal to xis equal to xcount(x)count(x)

Return the number of times x is in the listReturn the number of times x is in the listsort()sort()

Sort the items of the listSort the items of the list reverse()reverse()

Reverse the items of the listReverse the items of the list

Page 5: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Lists as StacksLists as Stacks

List methods make it easy to use lists as List methods make it easy to use lists as stacksstacks

The Stacks are formed with the last The Stacks are formed with the last element being added is the first element element being added is the first element retrieved retrieved (“last-in, first-out”) (“last-in, first-out”)

Use append() to add to the top of the stackUse append() to add to the top of the stackUse pop() to retrieve from the top of the Use pop() to retrieve from the top of the

stackstack

Page 6: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Lists as QueuesLists as Queues

Unlike sets, lists are not as efficient for forming Unlike sets, lists are not as efficient for forming QueuesQueues Appending and popping from the front of the list is Appending and popping from the front of the list is

slower than doing the same from the backslower than doing the same from the back

The Queues are formed with the first element The Queues are formed with the first element being added is the first element retrieved being added is the first element retrieved (“first-in, first-out”)(“first-in, first-out”)

Use collections.deque to implement a queueUse collections.deque to implement a queue This allows for faster access to both sides of the listThis allows for faster access to both sides of the list

Page 7: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Tools when using ListsTools when using Lists

filter(function, sequence)filter(function, sequence) Returns a sequence consisting of items from the sequence that Returns a sequence consisting of items from the sequence that

returns a true value for function(item)returns a true value for function(item) Outputs either a string, tuple, or listOutputs either a string, tuple, or list

If sequence is a string or tuple, it returns data of the same typeIf sequence is a string or tuple, it returns data of the same type If sequence is anything else it returns a listIf sequence is anything else it returns a list

map(function, sequence)map(function, sequence) Calls function(item) for each of the sequence’s itemsCalls function(item) for each of the sequence’s items

Returns a list of return values from the function(item) callReturns a list of return values from the function(item) call

reduce(function, sequence)reduce(function, sequence) Returns a single value constructed by calling the first two items Returns a single value constructed by calling the first two items

of a sequence, then the result and the next item until the of a sequence, then the result and the next item until the sequence is spentsequence is spent

Page 8: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

List ComprehensionsList Comprehensions

List comprehensions provide a concise way to create lists List comprehensions provide a concise way to create lists without resorting to the use of the aforementioned without resorting to the use of the aforementioned methods.methods.

Each list comprehension consists of an expression Each list comprehension consists of an expression followed by a for clause, then 0 or more for or if clauses.followed by a for clause, then 0 or more for or if clauses.

The result will be a list evaluated from the expression of The result will be a list evaluated from the expression of the for and if clauses.the for and if clauses. If the resulting list is to be converted into a Tuple, it If the resulting list is to be converted into a Tuple, it

must be parenthesized.must be parenthesized. List comprehensions are much more flexible that map() List comprehensions are much more flexible that map()

and can be applied to complex expressions and nested and can be applied to complex expressions and nested functionsfunctions

Page 9: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Tools when using ListsTools when using Lists

filter(function, sequence)filter(function, sequence) Returns a sequence consisting of items from the sequence that Returns a sequence consisting of items from the sequence that

returns a true value for function(item)returns a true value for function(item) Outputs either a string, tuple, or listOutputs either a string, tuple, or list

If sequence is a string or tuple, it returns data of the same typeIf sequence is a string or tuple, it returns data of the same type If sequence is anything else it returns a listIf sequence is anything else it returns a list

map(function, sequence)map(function, sequence) Calls function(item) for each of the sequence’s itemsCalls function(item) for each of the sequence’s items

Returns a list of return values from the function(item) callReturns a list of return values from the function(item) call

reduce(function, sequence)reduce(function, sequence) Returns a single value constructed by calling the first two items Returns a single value constructed by calling the first two items

of a sequence, then the result and the next item until the of a sequence, then the result and the next item until the sequence is spentsequence is spent

Page 10: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

The del StatementThe del Statement The del statement is a way to remove an item from a list The del statement is a way to remove an item from a list

given its index, instead of its valuegiven its index, instead of its value The del statement can be used to remove slices from a The del statement can be used to remove slices from a

list or clear an entire listlist or clear an entire list del can also be used to delete variablesdel can also be used to delete variables

del adel a If you reference the variable a after this, the program If you reference the variable a after this, the program

returns an errorreturns an error Unlike pop(), del does not return a valueUnlike pop(), del does not return a value

Page 11: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

TuplesTuples

Tuples – ordered list separated by commas Tuples – ordered list separated by commas Usually used in databases and formattingUsually used in databases and formatting Some information about TuplesSome information about Tuples

output Tuples are always enclosed in parenthesesoutput Tuples are always enclosed in parentheses Tuples are immutableTuples are immutable

Defining TuplesDefining Tuples Empty Tuples:Empty Tuples:

Empty = ()Empty = () Tuples with one value:Tuples with one value:

One = “hello”, One = “hello”,

Page 12: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

SetsSets

Sets – Unordered list that contain varying Sets – Unordered list that contain varying elementselements

Usually used in membership testing and Usually used in membership testing and eliminating duplicate informationeliminating duplicate information

Some information about sets:Some information about sets:Cannot contain duplicate informationCannot contain duplicate informationSet objects support mathematical Set objects support mathematical

operationoperation

Page 13: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

DictionariesDictionaries

Dictionaries – Unordered associative Dictionaries – Unordered associative arraysarrays

Dictionaries indexed by keys which can be Dictionaries indexed by keys which can be any immutable type such as int, string, or any immutable type such as int, string, or tupletupleYou cannot use lists as keysYou cannot use lists as keys

Dictionary’s keys must be uniqueDictionary’s keys must be uniqueDictionaries are unordered sets with a Dictionaries are unordered sets with a

key:value relationshipkey:value relationship

Page 14: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Dictionaries Cont.Dictionaries Cont.

Defining Dictionaries:Defining Dictionaries:Use curly brackets {}Use curly brackets {}Separate keys and values by :Separate keys and values by :A) dictest = { ‘first’ : ‘1st’, ‘second’ : ‘2nd’}A) dictest = { ‘first’ : ‘1st’, ‘second’ : ‘2nd’}B) dict(first=1st, second=2nd)B) dict(first=1st, second=2nd)A and B create the same DictionaryA and B create the same Dictionary

key()key()Returns all of the keys in the DictionaryReturns all of the keys in the Dictionary

Page 15: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Looping TechniquesLooping Techniques iteritems() iteritems()

Used for printing the keys and values of a dictionary while Used for printing the keys and values of a dictionary while loopinglooping

enumerate()enumerate() Used for printing the index and value of a list while loopingUsed for printing the index and value of a list while looping

zip()zip() To loop over two or more lists at the same timeTo loop over two or more lists at the same time

reverse()reverse() To loop over a list in reverseTo loop over a list in reverse

sorted()sorted() To loop over a list in sorted orderTo loop over a list in sorted order

Page 16: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

ConditionsConditions

The conditions used in while and if The conditions used in while and if statements can contain any operators, not statements can contain any operators, not just comparisons. just comparisons. Comparison operators have a lower priority Comparison operators have a lower priority

than mathematical operatorsthan mathematical operatorsComparisons can be chainedComparisons can be chained

a < b < ca < b < cChecks to see if a is less than b, than if b is less Checks to see if a is less than b, than if b is less

than c.than c.

Page 17: Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group

Conditions Cont.Conditions Cont.

In & not in check to see if values exist in a In & not in check to see if values exist in a list or sequencelist or sequence

Is & is not check to see if two values are Is & is not check to see if two values are equalequal

AND, OR, and NOT can all be used to AND, OR, and NOT can all be used to combine multiple comparisonscombine multiple comparisonsParenthesis can be used for groupingParenthesis can be used for groupingThe operators are tested left to rightThe operators are tested left to right