A list can also be empty: empty_list = [] Lists are similar to strings, but there are a few key differences.

Size: px
Start display at page:

Download "A list can also be empty: empty_list = [] Lists are similar to strings, but there are a few key differences."

Transcription

1 Chap 7 Python Lists and Dictionaries Introduction to Lists Lists are a data type you can use to store a collection of different pieces of information as a sequence under a single variable name. (Data type: strings, numbers, and Booleans) Assign items to a list with an expression of the form with the items in between brackets: list_name = [item_1, item_2] A list can also be empty: empty_list = [] Lists are similar to strings, but there are a few key differences. zoo_animals = ["pangolin", "cassowary", "sloth", "panda"]; Access by Index Access an individual item on the list by its index. An index is like an address that identifies the item s place in the list. The index (starts from 0) appears directly after the list name, in between brackets, like: list_name[index] numbers = [1,9,9,2,0,3,1,8] print numbers[2] + numbers[6] # = 10 New Neighbors A list index behaves like any other variable name. It can be used to access as well as assign values. 01. Access a list value: zoo_animals[0] 02. Assign a value to an item in a list: zoo_animals[2] = hyena # changes the original value to a new value Late Arrivals & List Length A list doesn t have to have a fixed length. You can add items to the end of a list any time by using append(). letters = [ a, b, c, d ] letters.append( e ) print len(letters)

2 print letters suitcase = [] suitcase.append("sunglasses") suitcase.append('flops') suitcase.append('towel') suitcase.append('swimming suit') list_length = len(suitcase) # Set this to the length of the suitcase list print "There are %d items in the suitcase." % (list_length) print suitcase List Slicing Sometimes, only want to access a portion of a list. Start at the index before the colon and continue up to but not including the index after the colon. letters = ['a', 'b', 'c', 'd', 'e'] slice = letters[1:3] # take a subsection and store it in the slice list # starts at the 1 index item ( b ) but not includes the 3 index item ( d ) print slice print letters # a portion items of the list [ b, c ] # ['a', 'b', 'c', 'd', 'e'] suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"] first = suitcase[0:2] middle = suitcase[2:4] last = suitcase[4:6] # The first and second items (index zero and one) # Third and fourth items (index two and three) # The last two items (index four and five)

3 Slicing Lists and Strings You can slice a string exactly like a list. Think of strings as lists of characters: each character is a sequential item in the list, string from index 0. my_list[:2] my_list[3:] # grabs the first two items # grabs the forth through last items If your list slice includes the very first or last item in a list (or a string), the index for that item doesn t have to be included. animals = "catdogfrog" cat = animals[:3] dog = animals[3:6] frog = animals[6:] # The first three characters of animals # The fourth through sixth characters # From the seventh character to the end Maintaining Order Sometimes you need to search for an item in a list: animals = [ ant, bat, cat ] print animals.index( bat ) # prints the index that contains the string Insert items into a list: animals.insert(1, dog ) print animals # [ ant, dog, bat, cat ] animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # use a variable to store the index of the string animals.insert(duck_index, 'cobra') # use the above variable as the index argument

4 print animals # ['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox'] For One and All If want to do sth. with every item in the list, use a for loop. The for loops in Python are different from loops in JavaScript. Syntax: for variable in list_name: # Do stuff! A variable name follows the for keyword; it will be assigned the value of each list item in turn. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list. my_list = [1,9,3,8,5,7] for number in my_list: print 2 * number # 2, 18, 6, 16, 10, 14 More with for If the list is a jumbled mess, you may need to sort() it. animals = ["cat", "ant", "bat"] animals.sort() # sort the list in alphabetical order for animal in animals: print animal # ["ant"] ["bat"] ["cat"] on separated lines start_list = [5, 3, 1, 2, 4] square_list = [] for x in start_list: # x is just a holdplace and it will be replaced by the items in the list square_list.append(number ** 2)

5 square_list.sort() print start_list # [5, 3, 1, 2, 4] print square_list # [1, 4, 9, 16, 25] This Next Part is Key You access values by looking up a key instead of an index. Dictionaries are enclosed in curly braces, like so: d = {'key1' : 1, 'key2' : 2, 'key3' : 3} This is a dictionary called d with 3 key-value pairs. The key1 points to the value 1. Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an address with a username), and more. Accessing the dictionary values by key is just like accessing list values by index: residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} print residents['puffin'] # gets the value 104 New Entries Like Lists, Dictionaries are mutable. This means they can be changed after they are created. One advantage of this is that we can add new key/value pairs to the dictionary after it is created like so: dict_name[new key] = new_value An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list. dict_name = {} The len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a list. (You can put lists inside dictionaries!) len(dic_name) menu = {} menu['chicken Alfredo'] = # Empty dictionary # Adding new key-value pair

6 print menu['chicken Alfredo'] #14.50 menu['broccoli Beef'] = menu['fired Rice'] = menu['dumplings'] = menu['pastry'] = 6.50 print "There are " + str(len(menu)) + " items on the menu." print menu # There are 5 items on the menu. # {'Dumplings': 11.5, 'Chicken Alfredo': 14.5, 'Broccoli Beef': 12.5, 'Fired Rice': 10.0, 'Pastry': 6.5} Changing Your Mind Items can be removed from a dictionary with the del command: (just can remove items one by one, cannot remove several items at a time) del dict_name[key_name] # removes the key and its associated value from the dictionary A new value can be associated with a key by assigning a value to the key, like so: dict_name[key] = new_value del zoo_animals['sloth'] del zoo_animals['bengal Tiger'] zoo_animals['rockhopper Penguin']='panda' Remove a Few Things Sometimes need to remove sth. from a list:.remove(item) beatles = ["john","paul","george","ringo","stuart"]

7 beatles.remove("stuart") print beatles # ["john","paul","george","ringo"] More Notes about Dictionaries Go over a few last notes about dictionaries: 01. Get the value from a list under a key in libraries dict_name[ key_name ][ index ] my_dict = { # create a dictionary that holds many types of values "fish": ["c", "a", "r", "p"], "cash": -4483, "luck": "good" } # a list # an int # a string print my_dict["fish"][0] # prints out the first item (0 index) in the fish list c Use list functions with a list stored in a dictionary as follows: dict_name[ list_key ].list_function() inventory = { 'gold' : 500, # An int variable 'pouch' : ['flint', 'twine', 'gemstone'], # A list 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'] } # A list # Adding a key 'burlap bag' and assigning a list to it inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth'] # Sorting the list found under the key 'pouch' inventory['pouch'].sort() # Adding a key pocket and assigning a list to it

8 inventory['pocket']=['seashell', 'strange berry', 'lint'] # Sorting the list found under the key backpack inventory['backpack'].sort() # Removing the dagger item from the backpack list inventory['backpack'].remove('dagger') # Adding 50 to the number stored under the gold key inventory['gold']+= 50 print inventory # {'pocket': ['seashell', 'strange berry', 'lint'], 'backpack': ['bedroll', 'bread loaf', 'xylophone'], 'pouch': ['flint', 'gemstone', 'twine'], 'burlap bag': ['apple', 'small ruby', 'three-toed sloth'], 'gold': 550} Chap 7 Exercise: A Day at the Supermarket BeFOR We Begin Go over the for loop in terms of how it relates to lists and dictionaries. for loops allow us to iterate through all the elements in a list from the left-most (or zeroth element) to the right-most element. A sample loop would be structured as follows: a = [ List of some sort ] for x in a: # Do sth. for every x The loop will run all of the code in the indented block. The item in the list that is currently being evaluated will be x. The variable between for and in can be set to any variable name (currently item), but should be careful to avoid using list as a

9 variable, since that s a reserved word (that is, it means sth. special) in the Python language. names = ["Adam","Alex","Mariah","Martine","Columbus"] for name in names: print name This is KEY! Use a for loop on a dictionary to loop through its keys with the following: # A simple dictionary d = { foo : bar } for key in d: print d[key] # prints bar Dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order. Control Flow and Looping The blocks of code in a for loop can be as big or as small as they need to be. While looping, you may want to perform different actions depending on the particular item in the list. numbers = [1,3,4,7] for number in numbers: if number > 6: # add a condition print number # prints 7 a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] for number in a: if number % 2 == 0:

10 print number # prints out the even number in a list Lists + Functions Functions can also take lists as inputs and perform various operations on those lists. def count_small(numbers): # declare a function count_small() with a numbers argument total = 0 for n in numbers: if n < 10: total +=1 # total = total + 1 return total lost = [4,8,15,16,23,42] small = count_small(lost) # declare a lost list/array # call the count_small function with a list argument print small # 4+8 = 12 def fizz_count(x): # declare a function fizz_count with one argument x count = 0 for item in x: if item == "fizz": count += 1 return count print fizz_count(["fizz", "cat", "fizz"]) # call the function with a list argument

11 String Looping Strings are like lists with characters as elements. You can loop through strings the same way you loop through lists. for letter in "Codecademy": # think of the string as a list of character elements print letter print # Empty lines to make the output pretty print word = "Programming is fun!" for letter in word: if letter == "i": # Only print out the letter i print letter Your Own Store! Create a dictionary called animal_counts with 3 entries with keys and values. Syntax: DictionaryName = { Key1 : Value1, Key2 : Value2 } animal_counts = { ant : 3, bear : 6, crow : 2 } Investing in Stock

12 prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } Keeping Track of the Produce Print out all of your inventory information. once = {'a': 1, 'b': 2} # create two dictionaries with the same keys twice = {'a': 2, 'b': 4} for key in once: # with the same keys, just loop through one dictionary and prints values from both two dictionaries print "Once: %s" % once[key] print "Twice: %s" % twice[key]

13 for key in prices: print key print "price: %s" % prices[key] # banana # price: 4 (the value under the key) print "stock: %s" % stock[key] # stock: 6 Something of Value Record the total value of the inventory. total = 0 # declares a global variable total and initializes it to 0 for key in prices: print key print "price: %s" % prices[key] print "stock: %s" % stock[key] print prices[key] * stock[key] sum = prices[key] * stock[key] total +=sum # print sum for each category # declares a local variable sum # total = total + sum print total # Shopping at the Market In order for customers to order online, we are going to have to make a consumer interface. 01. Make a list groceries = ["banana", "apple", "orange"] 02. Make a purchase <example> def sum(numbers): total = 0

14 for number in numbers: # for each number in the list, add that number to the running sum total total += number return total n = [1, 2, 5, 10, 13] print sum(n) shopping_list = ["banana", "orange", "apple"] def compute_bill(food): # declare a function with a food argument total = 0 for item in food: # loop through the food arugment total +=prices[item] # prices is a list of food price, with the same keys as the food argument return total Stocking Out Take the stock/inventory of a particular item into account when computing the cost. If an item isn t in stock, then it shouldn t be included in the total. def compute_bill(food): total = 0 for item in food: if stock[item] > 0: # check the inventory for each item total +=prices[item]

15 stock[item] -= 1 # subtract 1 from the inventory record return total Let s Check Out! Recap: 01.Using for loops with lists and dictionaries 02.Writing functions with loops, lists, and dictionaries 03.Updating data in response to changes in the environment (for instance, decreasing the number of amount in stock by 1 when you sell an item)

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Chapter 8 Dictionaries Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Creating a Dictionary To create a dictionary, you need

More information

Notebook. March 30, 2019

Notebook. March 30, 2019 Notebook March 30, 2019 1 Complex Data Types Some kinds of data can store other kinds of data. 1.1 Lists We ve actually seen the most common complex data type a few times before, I just haven t pointed

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH Introduction to Python Ph.D. Scien5fic Compu5ng Consultant PACE GATECH Things Covered What is Python? How to access Python environment? Fundamental elements in Python Variables (assignment, comparison,

More information

Introduction to Bioinformatics

Introduction to Bioinformatics Introduction to Bioinformatics Variables, Data Types, Data Structures, Control Structures Janyl Jumadinova February 3, 2016 Data Type Data types are the basic unit of information storage. Instances of

More information

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value. Data Structures Lists - stores a series of ordered mutable items Tuples - stores a series of ordered immutable items [not commonly used] Sets - stores a series of mutable or immutable(frozen) unsorted

More information

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Data Science Python. Anaconda.  Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas. Data Science Python Anaconda Python 3.x Includes ALL major Python data science packages Sci-kit learn Pandas PlotPy Jupyter Notebooks www.anaconda.com Python - simple commands Python is an interactive

More information

CSC Software I: Utilities and Internals. Programming in Python

CSC Software I: Utilities and Internals. Programming in Python CSC 271 - Software I: Utilities and Internals Lecture #8 An Introduction to Python Programming in Python Python is a general purpose interpreted language. There are two main versions of Python; Python

More information

Compound Data Types 2

Compound Data Types 2 Compound Data Types 2 Chapters 10, 11, 12 Prof. Mauro Gaspari: gaspari@cs.unibo.it Objects and Values We know that a and b both refer to a string, but we don t know whether they refer to the same string.

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

All programs can be represented in terms of sequence, selection and iteration.

All programs can be represented in terms of sequence, selection and iteration. Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational

More information

Unit E Step-by-Step: Programming with Python

Unit E Step-by-Step: Programming with Python Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator

More information

Compound Data Types 1

Compound Data Types 1 Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Overview.

Overview. Overview day one 0. getting set up 1. text output and manipulation day two 2. reading and writing files 3. lists and loops day three 4. writing functions 5. conditional statements day four today day six

More information

CS 234 Python Review Part 2

CS 234 Python Review Part 2 CS 234 Python Review Part 2 Recap import function: define, return boolean, conditional, branching loop: for, range, while file: open, close, readlines string: split Classes Define blueprint for a custom

More information

LECTURE 3 Python Basics Part 2

LECTURE 3 Python Basics Part 2 LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Here is a simple dictionary in Python. Let s store the telephone dialing codes for a few countries.

Here is a simple dictionary in Python. Let s store the telephone dialing codes for a few countries. 1 DICTIONARIES, TUPLES and SETS Python is renowned for its data types that allow us to store a collection of data. The most popular of these is the list, which you have already seen. A list is a collection

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Python Review IPRE

Python Review IPRE Python Review Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

Python Review IPRE

Python Review IPRE Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries

More information

CS Advanced Unix Tools & Scripting

CS Advanced Unix Tools & Scripting & Scripting Spring 2011 Hussam Abu-Libdeh slides by David Slater March 4, 2011 Hussam Abu-Libdeh slides by David Slater & Scripting Python An open source programming language conceived in the late 1980s.

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives To learn about

More information

Dictionaries. Upsorn Praphamontripong. CS 1111 Introduction to Programming Spring 2018

Dictionaries. Upsorn Praphamontripong. CS 1111 Introduction to Programming Spring 2018 Dictionaries Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 How do Computer Programs Fit in with the World Around Them? Thing (object type): Hotel Thing (object type): Car Thing

More information

Python 1: Intro! Max Dougherty Andrew Schmitt

Python 1: Intro! Max Dougherty Andrew Schmitt Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and

More information

Program Planning, Data Comparisons, Strings

Program Planning, Data Comparisons, Strings Program Planning, Data Comparisons, Strings Program Planning Data Comparisons Strings Reading for this class: Dawson, Chapter 3 (p. 80 to end) and 4 Program Planning When you write your first programs,

More information

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

Zipf's Law. This preliminary discussion gives us our first ideas about what the program we're writing needs to do.

Zipf's Law. This preliminary discussion gives us our first ideas about what the program we're writing needs to do. Zipf's Law In this unit, we'll be verifying the pattern of word frequencies known as Zipf's Law. Zipf's idea was pretty simple. Imagine taking a natural language corpus and making a list of all the words

More information

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food CSCI 1101B Lists Warm-up Exercise def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food food = order( pasta ) After this program runs 1. What is the global

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Priming Reads Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives

More information

Play with Python: An intro to Data Science

Play with Python: An intro to Data Science Play with Python: An intro to Data Science Ignacio Larrú Instituto de Empresa Who am I? Passionate about Technology From Iphone apps to algorithmic programming I love innovative technology Former Entrepreneur:

More information

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

PROBLEM SOLVING 11. July 24, 2012

PROBLEM SOLVING 11. July 24, 2012 PROBLEM SOLVING 11 COMPUTER SCIENCE 61A July 24, 2012 Today s section will be a kind of Meta-Section, we are going to walk through some medium to hard-ish problems in Scheme, and we will discuss some methods

More information

S206E Lecture 21, 5/26/2016, Python classes

S206E Lecture 21, 5/26/2016, Python classes S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Python has the notions of classes and objects from using dictionaries and modules to facilitate repetitious tasks. Information

More information

Variables and Data Representation

Variables and Data Representation You will recall that a computer program is a set of instructions that tell a computer how to transform a given set of input into a specific output. Any program, procedural, event driven or object oriented

More information

CSIS 10B Assignment 15 Maps and Hashing Due: next Wed

CSIS 10B Assignment 15 Maps and Hashing Due: next Wed CSIS 10B Assignment 15 Maps and Hashing Due: next Wed In class Demos (0 points) We develop a SimpleHashMap class: 1) built from an Array of Associations 2) experiment with different hash methods 3) put,

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #5 is due today Homework #6 is out and DUE on MONDAY (3/5)

More information

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

Quiz 1: Functions and Procedures

Quiz 1: Functions and Procedures Quiz 1: Functions and Procedures Outline Basics Control Flow While Loops Expressions and Statements Functions Primitive Data Types 3 simple data types: number, string, boolean Numbers store numerical data

More information

Math 1MP3, midterm test February 2017

Math 1MP3, midterm test February 2017 Math 1MP3, midterm test 2017 17 February 2017 Please write your name, student number, and MacID on this test and on your answer booklet. Please circle your family name, e.g. Fred Q. Student, 00045234,

More information

Problem Solving for Intro to Computer Science

Problem Solving for Intro to Computer Science Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample

More information

Scripting Languages Course 1. Diana Trandabăț

Scripting Languages Course 1. Diana Trandabăț Scripting Languages Course 1 Diana Trandabăț Master in Computational Linguistics - 1 st year 2017-2018 Today s lecture Introduction to scripting languages What is a script? What is a scripting language

More information

Using Lists (Arrays) Notes

Using Lists (Arrays) Notes Using Lists (Arrays) Notes - 27.11.16 Array/List = a data structure that allows for multiplied items or elements to be stored using just one variable name. Each element in a list is accessed using an index

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

More information

List Processing Patterns and List Comprehension

List Processing Patterns and List Comprehension List Processing Patterns and Review: Lists Summary of what we know about lists. A list is a sequence type (like strings and tuples), but that differently from them is mutable (it can change). Lists can

More information

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

The second statement selects character number 1 from and assigns it to.

The second statement selects character number 1 from and assigns it to. Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 06 Arrays MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Array An array is a group of variables (called elements or components) containing

More information

An introduction to Python

An introduction to Python supported by Abstract This guide provides a simple introduction to Python with examples and exercises to assist learning. Python is a high level object-oriented programming language. Data and functions

More information

3. Conditional Execution

3. Conditional Execution 3. Conditional Execution Topics: Boolean values Relational operators if statements The Boolean type Motivation Problem: Assign positive float values to variables a and b and print the values a**b and b**a.

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 09 For Loops All materials copyright UMBC unless otherwise noted Last Class We Covered Lists and what they are used for Operations a list can perform Including

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java expressions and operators concluded Java Statements: Conditionals: if/then, if/then/else Loops: while, for Next

More information

Chapter 2: Lists, Arrays and Dictionaries

Chapter 2: Lists, Arrays and Dictionaries Chapter 2: Lists, Arrays and Dictionaries 1. Higher order organization of data In the previous chapter, we have seen the concept of scalar variables that define memory space in which we store a scalar,

More information

Using Scala in CS241

Using Scala in CS241 Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Table of Contents Introduction!... 1 Part 1: Entering Data!... 2 1.a: Typing!... 2 1.b: Editing

More information

CSE 160 Winter 2016: Final Exam

CSE 160 Winter 2016: Final Exam Name: Email address (UW NetID): CSE 160 Winter 2016: Final Exam (closed book, closed notes, no calculators) Instructions: This exam is closed book, closed notes. You have 50 minutes to complete it. It

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han Lesson 4: Type Conversion, Mutability, Sequence Indexing Fundamentals of Text Processing for Linguists Na-Rae Han Objectives Python data types Mutable vs. immutable object types How variable assignment

More information

List Processing Patterns and List Comprehension

List Processing Patterns and List Comprehension List Processing Patterns and List Comprehension Review: Lists Summary of what we know about lists. A list is a sequence type (like strings and tuples), but that differently from them is mutable (it can

More information

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas Introduction to Python Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas If you have your own PC, download and install a syntax-highlighting text editor and Python

More information

Abstract Data Types Chapter 1

Abstract Data Types Chapter 1 Abstract Data Types Chapter 1 Part Two Bags A bag is a basic container like a shopping bag that can be used to store collections. There are several variations: simple bag grab bag counting bag 2 Bag ADT

More information

Basic Python Revision Notes With help from Nitish Mittal

Basic Python Revision Notes With help from Nitish Mittal Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring

More information

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 15 For Loops All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Last Class We Covered Two-dimensional lists Lists and functions Mutability

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

3. Conditional Execution

3. Conditional Execution 3. Conditional Execution Topics: Boolean values Relational operators if statements The Boolean type Motivation Problem: Assign positive float values to variables a and b and print the values a**b and b**a.

More information

CS1 Lecture 11 Feb. 9, 2018

CS1 Lecture 11 Feb. 9, 2018 CS1 Lecture 11 Feb. 9, 2018 HW3 due Monday morning, 9:00am for #1 I don t care if you use 1, 2, or 3 loops. Most important is clear correct code for #3, make sure all legal situations are handled. Think

More information

Unit 2. Srinidhi H Asst Professor

Unit 2. Srinidhi H Asst Professor Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th. 6.189 Homework 3 Readings How To Think Like A Computer Scientist: Monday - chapters 9, 10 (all); Tuesday - Chapters 12, 13, 14 (all). Tuesday s reading will really help you. If you re short on time, skim

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

(CC)A-NC 2.5 by Randall Munroe Python

(CC)A-NC 2.5 by Randall Munroe Python http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional

More information

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below. Name: Date: Instructions: PYTHON - INTRODUCTORY TASKS Open Idle (the program we will be using to write our Python codes). We can use the following code in Python to work out numeracy calculations. Try

More information

Chapter 10: Strings and Hashtables

Chapter 10: Strings and Hashtables Chapter 10: Strings and Hashtables This chapter describes the string and hashtable data types in detail. Strings hold text-- words and phrases-- and are used in all applications with natural language processing.

More information

CSE 160 Winter 2016: Final Exam

CSE 160 Winter 2016: Final Exam Name: Sample Solution Email address (UW NetID): CSE 160 Winter 2016: Final Exam (closed book, closed notes, no calculators) Instructions: This exam is closed book, closed notes. You have 50 minutes to

More information

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas Introduction to Python Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas If you have your own PC, download and install a syntax-highlighting text editor and Python

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Python Lists: Example 1: >>> items=[apple, orange,100,25.5] >>> items[0] 'apple' >>> 3*items[:2] Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.

More information