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.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Container Types in Python
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Dictionaries: Keeping track of pairs
Tuples. Tuples 1 A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only difference is that tuples can't be.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Guide to Programming with Python
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Sequences The range function returns a sequence
Sequences A sequence is a list of elements Lists and tuples
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Chapter 24 Dispensers and dictionaries. This chapter discusses n Dictionaries n Dispensers u stacks u queues u priority queues.
Data Structures Akshay Singh.  Lists in python can contain any data type  Declaring a list:  a = [‘random’,’variable’, 1, 2]
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Week7 Stack Data Structures & Algorithms. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Python Data Structures
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Beyond Lists: Other Data Structures CS303E: Elements of Computers and Programming.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Daniel Jung. Types of Data Structures  Lists Stacks Queues  Tuples  Sets  Dictionaries.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Tuples Chapter 10 Python for Informatics: Exploring Information
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
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.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Python Fundamentals: Complex Data Structures Eric Shook Department of Geography Kent State University.
String and Lists Dr. José M. Reyes Álamo.
Python Variable Types.
Lecture 3 Python Basics Part 2.
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
LING 388: Computers and Language
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
8 – Lists and tuples John R. Woodward.
Python Data Structures
Python for Informatics: Exploring Information
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Python Review
For loop Using lists.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Sample lecture slides.
Dictionary.
Python List.
Python - Tuples.
Introduction to Computer Science
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

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 of comma-separated values between square brackets. The values can be of multiple types: such as strings, ints, or other lists. The values can be of multiple types: such as strings, ints, or other lists. Lists start at the indices 0 Lists start at the indices 0 Defining 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]

Methods of a List len() len() Gives the size of the list Gives the size of the list append() append() Adds an item to the end of the list Adds an item to the end of the list extend(L) extend(L) Extend the list by appending all the items Extend the list by appending all the items remove(x) remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item. Remove the first item from the list whose value is x. It is an error if there is no such item. pop([i]) pop([i]) Remove the item at the given position in the list Remove the item at the given position in the list

Methods of a List index(x) index(x) Return the index of the first item whose value is equal to x Return the index of the first item whose value is equal to x count(x) count(x) Return the number of times x is in the list Return the number of times x is in the list sort() sort() Sort the items of the list Sort the items of the list reverse() reverse() Reverse the items of the list Reverse the items of the list

Lists as Stacks List methods make it easy to use lists as stacks List methods make it easy to use lists as stacks The Stacks are formed with the last element being added is the first element retrieved The Stacks are formed with the last element being added is the first element retrieved (“last-in, first-out”) (“last-in, first-out”) Use append() to add to the top of the stack Use append() to add to the top of the stack Use pop() to retrieve from the top of the stack Use pop() to retrieve from the top of the stack

Lists as Queues Unlike sets, lists are not as efficient for forming Queues Unlike sets, lists are not as efficient for forming Queues Appending and popping from the front of the list is slower than doing the same from the back Appending and popping from the front of the list is slower than doing the same from the back The Queues are formed with the first element being added is the first element retrieved The Queues are formed with the first element being added is the first element retrieved (“first-in, first-out”) (“first-in, first-out”) Use collections.deque to implement a queue Use collections.deque to implement a queue This allows for faster access to both sides of the list This allows for faster access to both sides of the list

Tools when using Lists filter(function, sequence) filter(function, sequence) Returns a sequence consisting of items from the sequence that returns a true value for function(item) Returns a sequence consisting of items from the sequence that returns a true value for function(item) Outputs either a string, tuple, or list Outputs either a string, tuple, or list If sequence is a string or tuple, it returns data of the same type If sequence is a string or tuple, it returns data of the same type If sequence is anything else it returns a list If sequence is anything else it returns a list map(function, sequence) map(function, sequence) Calls function(item) for each of the sequence’s items Calls function(item) for each of the sequence’s items Returns a list of return values from the function(item) call Returns 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 of a sequence, then the result and the next item until the sequence is spent Returns a single value constructed by calling the first two items of a sequence, then the result and the next item until the sequence is spent

List Comprehensions List comprehensions provide a concise way to create lists without resorting to the use of the aforementioned methods. List comprehensions provide a concise way to create lists without resorting to the use of the aforementioned methods. Each list comprehension consists of an expression followed by a for clause, then 0 or more for or if clauses. Each list comprehension consists of an expression 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 for and if clauses. The result will be a list evaluated from the expression of the for and if clauses. If the resulting list is to be converted into a Tuple, it must be parenthesized. If the resulting list is to be converted into a Tuple, it must be parenthesized. List comprehensions are much more flexible that map() and can be applied to complex expressions and nested functions List comprehensions are much more flexible that map() and can be applied to complex expressions and nested functions

Tools when using Lists filter(function, sequence) filter(function, sequence) Returns a sequence consisting of items from the sequence that returns a true value for function(item) Returns a sequence consisting of items from the sequence that returns a true value for function(item) Outputs either a string, tuple, or list Outputs either a string, tuple, or list If sequence is a string or tuple, it returns data of the same type If sequence is a string or tuple, it returns data of the same type If sequence is anything else it returns a list If sequence is anything else it returns a list map(function, sequence) map(function, sequence) Calls function(item) for each of the sequence’s items Calls function(item) for each of the sequence’s items Returns a list of return values from the function(item) call Returns 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 of a sequence, then the result and the next item until the sequence is spent Returns a single value constructed by calling the first two items of a sequence, then the result and the next item until the sequence is spent

The del Statement The del statement is a way to remove an item from a list given its index, instead of its value The del statement is a way to remove an item from a list given its index, instead of its value The del statement can be used to remove slices from a list or clear an entire list The del statement can be used to remove slices from a list or clear an entire list del can also be used to delete variables del can also be used to delete variables del a del a If you reference the variable a after this, the program returns an error If you reference the variable a after this, the program returns an error Unlike pop(), del does not return a value Unlike pop(), del does not return a value

Tuples Tuples – ordered list separated by commas Tuples – ordered list separated by commas Usually used in databases and formatting Usually used in databases and formatting Some information about Tuples Some information about Tuples output Tuples are always enclosed in parentheses output Tuples are always enclosed in parentheses Tuples are immutable Tuples are immutable Defining Tuples Defining Tuples Empty Tuples: Empty Tuples: Empty = () Empty = () Tuples with one value: Tuples with one value: One = “hello”, One = “hello”,

Sets Sets – Unordered list that contain varying elements Sets – Unordered list that contain varying elements Usually used in membership testing and eliminating duplicate information Usually used in membership testing and eliminating duplicate information Some information about sets: Some information about sets: Cannot contain duplicate information Cannot contain duplicate information Set objects support mathematical operation Set objects support mathematical operation

Dictionaries Dictionaries – Unordered associative arrays Dictionaries – Unordered associative arrays Dictionaries indexed by keys which can be any immutable type such as int, string, or tuple Dictionaries indexed by keys which can be any immutable type such as int, string, or tuple You cannot use lists as keys You cannot use lists as keys Dictionary’s keys must be unique Dictionary’s keys must be unique Dictionaries are unordered sets with a key:value relationship Dictionaries are unordered sets with a key:value relationship

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 Dictionary A and B create the same Dictionary key() key() Returns all of the keys in the Dictionary Returns all of the keys in the Dictionary

Looping Techniques iteritems() iteritems() Used for printing the keys and values of a dictionary while looping Used for printing the keys and values of a dictionary while looping enumerate() enumerate() Used for printing the index and value of a list while looping Used for printing the index and value of a list while looping zip() zip() To loop over two or more lists at the same time To loop over two or more lists at the same time reverse() reverse() To loop over a list in reverse To loop over a list in reverse sorted() sorted() To loop over a list in sorted order To loop over a list in sorted order

Conditions The conditions used in while and if statements can contain any operators, not just comparisons. The conditions used in while and if statements can contain any operators, not just comparisons. Comparison operators have a lower priority than mathematical operators Comparison operators have a lower priority than mathematical operators Comparisons can be chained Comparisons can be chained a < b < c a < b < c Checks to see if a is less than b, than if b is less than c. Checks to see if a is less than b, than if b is less than c.

Conditions Cont. In & not in check to see if values exist in a list or sequence In & not in check to see if values exist in a list or sequence Is & is not check to see if two values are equal Is & is not check to see if two values are equal AND, OR, and NOT can all be used to combine multiple comparisons AND, OR, and NOT can all be used to combine multiple comparisons Parenthesis can be used for grouping Parenthesis can be used for grouping The operators are tested left to right The operators are tested left to right