Built-in Data Structures in Python An Introduction.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

Container Types in Python
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
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.
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.
Python Dictionary.
Sequences The range function returns a sequence
Lists Introduction to Computing Science and Programming I.
Sequences A sequence is a list of elements Lists and tuples
1 Sequences A sequence is a list of elements Lists and tuples – Lists mutable – Tuples immutable Sequence elements can be indexed with subscripts – First.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Python Crash Course Containers 3 rd year Bachelors V1.0 dd Hour 3.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Lists in Python.
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.
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.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
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.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
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.
Lists. The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets.
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.
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 Programing: An Introduction to Computer Science
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.
INTRO2CS Tirgul 4 1. What will we see today?  Strings  Lists  Tuples  Mutable and Immutable  Iterating over sequences  Nested Loops  Shallow and.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
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.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
String and Lists Dr. José M. Reyes Álamo.
10 - Python Dictionary John R. Woodward.
Python Variable Types.
Tuples and Lists.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CISC101 Reminders Quiz 2 this week.
Topics Introduction to File Input and Output
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
8 – Lists and tuples John R. Woodward.
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
15-110: Principles of Computing
Topics Sequences Lists Copying Lists Processing Lists
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
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
For loop Using lists.
Topics Introduction to File Input and Output
Dictionary.
Introduction to Computer Science
Presentation transcript:

Built-in Data Structures in Python An Introduction

Python Data Structures There are four built-in data structures in Python List Tuple Dictionary Set. The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position, or index. The first index is zero, the second index is one, and so forth. We will see how to use each of them and how the make life easier for us.

Lists A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. The list of items should be enclosed in square brackets so that Python understands that you are specifying a list. Once you have created a list, you can add, remove or search for items in the list. Since we can add and remove items, we say that a list is a mutable data type i.e. this type can be altered. list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];

Accessing values in the list

Updating Lists You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator You can add to elements in a list with the append() method.

Updating list elements by slicing By specifying a[0:2] on the left side of the operator, you are telling python you want to use slice assignment, which is very similar to tuple unpacking. This is equivalent to: a[0], a[1] = [4, 5]tuple unpacking >>> a = [1, 2, 3] >>> a[0:0] = [-3, -2, -1, 0] >>> a [-3, -2, -1, 0, 1, 2, 3] >>> a[:] = [1, 2, 3] >>> a [1, 2, 3] >>> a[-1:] = [5, 4, 3, 2] >>> a [1, 2, 5, 4, 3, 2]

Negative List Indices accesses elements from the end of the list counting backwards. The last element of any non- empty list is always li[-1] >>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li[-1] 'example' >>> li[-3] 'mpilgrim‘ Slicing Shorthand >>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li[:3] ['a', 'b', 'mpilgrim'] >>> li[3:] ['z', 'example'] >>> li[:] ['a', 'b', 'mpilgrim', 'z', 'example']

Adding elements to the lists >>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li.append("new") >>> li ['a', 'b', 'mpilgrim', 'z', 'example', 'new'] >>> li.insert(2, "new") >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new'] >>> li.extend(["two", "elements"]) >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements'] Append adds a single element to the end of the list. Insert inserts a single element into a list to a particular position. Extend concatenates lists. Note that you do not call extend with multiple arguments; you call it with one argument, a list.

The Difference between extend and append “extend” takes a single argument, which is always a list, and adds each of the elements of that list to the original list. ”append” takes one argument, which can be any data type, and simply adds it to the end of the list. Here, you're calling the append method with a single argument, which is a list of three elements. Now the original list, which started as a list of three elements, contains four elements. Because the last element that you just appended is itself a list. Lists can contain any type of data, including other lists.

Example for extend & append >>> li = ['a', 'b', 'c'] >>> li.extend(['d', 'e', 'f']) >>> li ['a', 'b', 'c', 'd', 'e', 'f'] >>> len(li) 6 >>> li[-1] 'f' >>> li = ['a', 'b', 'c'] >>> li.append(['d', 'e', 'f']) >>> li ['a', 'b', 'c', ['d', 'e', 'f']] >>> len(li) 4 >>> li[-1] ['d', 'e', 'f']

Delete list of elements >>> a = [-1, 1, 66.25, 333, 333, ] >>> del a[0] >>> a [1, 66.25, 333, 333, ] >>> del a[2:4] >>> a [1, 66.25, ] >>> del a[:] >>> a []

Basic List operations

Remove elements from the list “remove” removes the first occurrence of a value from a list. If the value is not found in the list it raises an exception. Pop does two things: it removes the last element of the list, and it returns the value that it removed. Note that this is different from li[-1], which returns a value but does not change the list, and different from li.remove(value), which changes the list but does not return a value.

Example >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements'] >>> li.remove("z") >>> li ['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements'] >>> li.remove("new") >>> li ['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements'] >>> li.remove("c") Traceback (innermost last): File " ", line 1, in ? ValueError: list.remove(x): x not in list >>> li.pop() 'elements' >>> li ['a', 'b', 'mpilgrim', 'example', 'new', 'two']

Searching elements index finds the first occurrence of a value in the list and returns the index. >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements'] >>> li.index("example") 5 >>> li.index("new") 2 >>> li.index("c") Traceback (innermost last): File " ", line 1, in ? ValueError: list.index(x): x not in list >>> "c" in li False

Built-in List Functions

Built-in List Methods

List Comprehensions List comprehensions provide a concise way to create lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. The list comprehension always returns a result list.

The basic syntax is [ expression for item in list if conditional ] is equivalent to for item in list: if conditional: expression

Example-1 # You can either use loops: squares = [] for x in range(10): squares.append(x**2) print squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # Or you can use list comprehensions to get the same result: squares = [x**2 for x in range(10)] print squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Example-2 listOfWords = ["this","is","a","list","of","words"] items = [ word[0] for word in listOfWords] print items Output: ['t', 'i', 'a', 'l', 'o', 'w'] string = "Hello World" numbers = [x for x in string if x.isdigit()] print numbers Output: ['1', '2', '3', '4', '5‘]

Tuples--Introduction A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only difference is that tuples can't be changed ie. tuples are immutable Tuples use parentheses and lists use square brackets.

Example on Tuples

Tuples continued…. The empty tuple is written as two parentheses containing nothing: tup1 = (); To write a tuple containing a single value you have to include a comma, even though there is only one value: tup1 = (50,); Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.

Updating Tuples: Tuples are immutable which means you cannot update them or change values of tuple elements. But we able to take portions of an existing tuples to create a new tuples as follows. Following is a simple example:

Delete Tuple Elements: Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement. This produce the error as after “del tup” tuple does not exist any more

Python Dictionary A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values. Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows: Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Example

Output

Updating Dictionary

Delete Dictionary elements

Properties of Dictionary Keys More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary keys but something like ['key'] is not allowed.. Dictionary Keys Are Case-Sensitive

Built-in Dictionary Functions

Built-in Dictionary Methods

Python dictionary fromkeys() Method The method fromkeys() creates a new dictionary with keys from seq and values set to value. dict.fromkeys(seq[, value])) seq -- This is the list of values which would be used for dictionary keys preparation. value -- This is optional, if provided then value would be set to this value

Python dictionary get() Method The method get() return a value for the given key. If key is not available then returns default value None. dict.get(key, default=None)

Exercises Implement a stack and queue using lists Write a function find_longest_word() that takes a list of words and returns the length of the longest one using tuples. Write a function filter_long_words() that takes a list of words and an integer ’n’ and returns the list of words that are longer than ’n’. Create a dictionary state and their capitals and print capital for the given state. Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words. Write a tiny Python program numDict.py that makes a dictionary whose keys are the words ‘one’, ‘two’, ‘three’, and ‘four’, and whose corresponding values are the numerical equivalents, 1, 2, 3, and 4 (ints, not strings). Include code to test the resulting dictionary by referencing several of the definitions and printing the results. Write a program to convert list of Celsius values to Fahrenheit using list comprehension Write a program that creates the Pythagorean triples using list comprehension (x**2+y**2 = z**2) (you can use tuple to store the triples)