Container Types in Python

Slides:



Advertisements
Similar presentations
Python for Informatics: Exploring Information
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Course A201: Introduction to Programming 10/28/2010.
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
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.
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.
Sequences The range function returns a sequence
Lists Introduction to Computing Science and Programming I.
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.
Guide to Programming with Python
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
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.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Python I CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
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.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
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.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
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.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
1 Python Data Structures LING 5200 Computational Corpus Linguistics Martha Palmer.
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.
String and Lists Dr. José M. Reyes Álamo.
Python - Lists.
Containers and Lists CIS 40 – Introduction to Programming in Python
CS 100: Roadmap to Computing
CSc 120 Introduction to Computer Programing II
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CISC101 Reminders Quiz 2 this week.
Lists Part 1 Taken from notes by Dr. Neil Moore
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
Ruth Anderson University of Washington CSE 160 Spring 2018
Creation, Traversal, Insertion and Removal
Introduction to Python
Data types Numeric types Sequence types float int bool list str
8 – Lists and tuples John R. Woodward.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Python I Some material adapted from Upenn cmpe391 slides and other sources.
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Reference semantics, variables and names
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Introduction to Computer Science
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
CS 100: Roadmap to Computing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Computer Science
Presentation transcript:

Container Types in Python

Container Types We’ve talked about integers, floats, and strings… Containers are other built-in data types in Python. Can hold objects of any type (including their own type). There are three kinds of containers: Tuples A simple immutable ordered sequence of items. Lists Sequence with more powerful manipulations possible. Dictionaries A look-up table of key-value pairs.

Tuples, Lists, and Strings: Similarities

Similar Syntax Tuples and lists are sequential containers that share much of the same syntax and functionality. For conciseness, they will be introduced together. The operations shown in this section can be applied to both tuples and lists, but most examples will just show the operation performed on one or the other. While strings aren’t exactly a container data type, they also happen to share a lot of their syntax with lists and tuples; so, the operations you see in this section can apply to them as well.

Tuples, Lists, and Strings 1 Tuples are defined using parentheses (and commas). >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) Lists are defined using square brackets (and commas). >>> li = [“abc”, 34, 4.34, 23] Strings are defined using quotes (“, ‘, or “““). >>> st = “Hello World” >>> st = ‘Hello World’ >>> st = “““This is a multi-line string that uses triple quotes.”””

Tuples, Lists, and Strings 2 We can access individual members of a tuple, list, or string using square bracket “array” notation. >>> tu[1] # Second item in the tuple. ‘abc’ >>> li[1] # Second item in the list. 34 >>> st[1] # Second character in string. ‘e’

Looking up an Item >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Positive index: count from the left, starting with 0. >>> t[1] ‘abc’ Negative lookup: count from right, starting with –1. >>> t[-3] 4.56

Slicing: Return Copy of a Subset 1 >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Return a copy of the container with a subset of the original members. Start copying at the first index, and stop copying before the second index. >>> t[1:4] (‘abc’, 4.56, (2,3)) You can also use negative indices when slicing. >>> t[1:-1]

Slicing: Return Copy of a Subset 2 >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Omit the first index to make a copy starting from the beginning of the container. >>> t[:2] (23, ‘abc’) Omit the second index to make a copy starting at the first index and going to the end of the container. >>> t[2:] (4.56, (2,3), ‘def’)

Copying the Whole Container You can make a copy of the whole tuple using [:]. >>> t[:] (23, ‘abc’, 4.56, (2,3), ‘def’) So, there’s a difference between these two lines: >>> list2 = list1 # 2 names refer to 1 ref # Changing one affects both >>> list2 = list1[:] # Two copies, two refs # They’re independent

The ‘in’ Operator Boolean test whether a value is inside a container: >>> 3 in t False >>> 4 in t True >>> 4 not in t Be careful: the ‘in’ keyword is also used in the syntax of other unrelated Python constructions: “for loops” and “list comprehensions.”

The + Operator The + operator produces a new tuple, list, or string whose value is the concatenation of its arguments. >>> (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) >>> [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] >>> “Hello” + “ ” + “World” ‘Hello World’

The * Operator The * operator produces a new tuple, list, or string that “repeats” the original content. >>> (1, 2, 3) * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> “Hello” * 3 ‘HelloHelloHello’

Mutability: Tuples vs. Lists What’s the difference between tuples and lists?

Tuples: Immutable >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) >>> t[2] = 3.14 Traceback (most recent call last): File "<pyshell#75>", line 1, in -toplevel- tu[2] = 3.14 TypeError: object doesn't support item assignment You’re not allowed to change a tuple in place in memory; so, you can’t just change one element of it. But it’s always OK to make a fresh tuple and assign its reference to a previously used name. >>> t = (1, 2, 3, 4, 5)

Lists: Mutable >>> li = [‘abc’, 23, 4.34, 23] We can change lists in place. So, it’s ok to change just one element of a list. Name li still points to the same memory reference when we’re done.

Operations on Lists Only 1 Since lists are mutable (they can be changed in place in memory), there are many more operations we can perform on lists than on tuples. The mutability of lists also makes managing them in memory more complicated… So, they aren’t as fast as tuples. It’s a tradeoff.

Operations on Lists Only 2 >>> li.append(‘a’) >>> li [1, 2, 3, 4, 5, ‘a’] >>> li.insert(2, ‘i’) >>>li [1, 2, ‘i’, 3, 4, 5, ‘a’]

Operations on Lists Only 3 The ‘extend’ operation is similar to concatenation with the + operator. But while the + creates a fresh list (with a new memory reference) containing copies of the members from the two inputs, the extend operates on list li in place. >>> li.extend([9, 8, 7]) >>>li [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7] Extend takes a list as an argument. Append takes a singleton. >>> li.append([9, 8, 7]) >>> li [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [9, 8, 7]]

Operations on Lists Only 4 >>> li = [‘a’, ‘b’, ‘c’, ‘b’] >>> li.index(‘b’) # index of first occurrence 1 >>> li.count(‘b’) # number of occurrences 2 >>> li.remove(‘b’) # remove first occurrence >>> li [‘a’, ‘c’, ‘b’]

Operations on Lists Only 5 >>> li.reverse() # reverse the list *in place* >>> li [8, 6, 2, 5] >>> li.sort() # sort the list *in place* [2, 5, 6, 8] >>> li.sort(some_function) # sort in place using user-defined comparison

Tuples vs. Lists Lists slower but more powerful than tuples. Lists can be modified, and they have lots of handy operations we can perform on them. Tuples are immutable and have fewer features. We can always convert between tuples and lists using the list() and tuple() functions. li = list(tu) tu = tuple(li)

List Exercise

List of Turtles >>> from turtle import * >>> tl = [Turtle(), Turtle(), Turtle()] >>> tl[0].forward(25) >>> tl[1].color('red') >>> tl[1].left(90) >>> tl[1].forward(25) >>> for i in range (len(tl)): tl[i].forward(50)

List of Alien Counts def alienGame(): aliens=[['red',15], ['green',10], ['blue', 30], ['purple', 20]] for i in range(len(aliens)): print("There are " + str(aliens[i][1] )+ " " + aliens[i][0] + " aliens.") alienGame()

How would you create turtle aliens? use the turtle arrow shape as an abstraction for an alien use the list of aliens as an abstraction of the alien army

from turtle import * def alienGame(): aliens=[['red',15], ['green',10], ['blue', 30], ['purple', 20]] for i in range(len(aliens)): print("There are " + str(aliens[i][1] )+ " " + aliens[i][0] + " aliens.") for j in range(aliens[i][1]): t=Turtle() t.left(i*90) t.forward( j*10) t.color(aliens[i][0]) alienGame()