8 – Lists and tuples John R. Woodward.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

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.
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
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.
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.
Python Crash Course Containers 3 rd year Bachelors V1.0 dd Hour 3.
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.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! Topics to be covered in this lecture(s)
Strings CS303E: Elements of Computers and Programming.
Chapter 7 Lists and Tuples. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Data Structures.
Built-in Data Structures in Python An Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
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.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Lists CS303E: Elements of Computers and Programming.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
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.
INTRO2CS Tirgul 4 1. What will we see today?  Strings  Lists  Tuples  Mutable and Immutable  Iterating over sequences  Nested Loops  Shallow and.
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.
Intro2cs Tirgul 4.
String and Lists Dr. José M. Reyes Álamo.
Intro2cs Tirgul 3.
Topic: Python Lists – Part 1
CMSC201 Computer Science I for Majors Lecture 14 – Tuples
Tuples and Lists.
Containers and Lists CIS 40 – Introduction to Programming in Python
Lecture 10 Data Collections
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Strings
Introduction to Strings
Bryan Burlingame 03 October 2018
Lists in Python.
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Data types Numeric types Sequence types float int bool list str
Data Structures – 1D Lists
4. sequence data type Rocky K. C. Chang 16 September 2018
String and Lists Dr. José M. Reyes Álamo.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Sequences Introduction to Lists List Slicing
Introduction to Strings
15-110: Principles of Computing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Sequences Lists Copying Lists Processing Lists
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
And now for something completely different . . .
Introduction to Strings
Lecture 7: Python’s Built-in Types and Basic Statements
Python Review
CMSC201 Computer Science I for Majors Lecture 16 – Tuples
For loop Using lists.
Class code for pythonroom.com cchsp2cs
Introduction to Strings
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Computer Science
Presentation transcript:

8 – Lists and tuples John R. Woodward

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 []. Good (and bad) thing about a list is that items in a list need not all have the same type. Creating a list - put different comma-separated values between square brackets. list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];

Accessing Values in Lists To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. Following is a simple example: list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] it produces the following result: list1[0]: physics list2[1:5]: [2, 3, 4, 5]

Updating Lists You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. Following is a simple example: list = ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : " print list[2]; list[2] = 2001; print "New value available at index 2 : " print list[2];

Example list = [0,1,2,3,4,5,6] print list list[3] = 9 list[-1] = 0 #Output [0, 1, 2, 3, 4, 5, 6] [0, 1, 2, 9, 4, 5, 6] [0, 1, 2, 9, 4, 5, 0]

Del at item from a list print len(list) del list[3] print list #Output [0, 1, 2, 9, 4, 5, 0] 7 [0, 1, 2, 4, 5, 0] 6

Delete List Elements To remove a list element, you can use either the del statement list1 = ['physics', 'chemistry', 1997, 2000]; print list1; del list1[2]; print "After deleting value at index 2 : " #it produces following result: ['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000]

Delete a sub-list list = [1,2,3,4,5,6,7,8,9,0] print list del list[3:6] #Output [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] [1, 2, 3, 7, 8, 9, 0]

Basic List Operations Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration

Indexing Assuming following input: L = ['spam', 'Spam', 'SPAM!'] Python Expression Results Description L[2] 'SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in List Functions 1 Function with Description 1 cmp(list1, list2) Compares elements of both lists. 2 len(list) Gives the total length of the list. 3 max(list) Returns item from the list with max value. 4 min(list) Returns item from the list with min value. 5 list(seq) Converts a tuple into list.

Max – different data types print max([1,2,3,4,5,6,7]) print max([1,2.6,3,4.8]) print max(["a", "b", "c"]) print max(["a", "b", "c", 1, 2, 3]) #Outout 7 4.8 c

Cmp – compare two list (-1,0,1) print cmp(list1, list2) print cmp(list1, list3) print cmp(list3, list1) #output 1 -1

Built-in List Functions 2 Methods with Description list.append(obj) Appends object obj to list list.count(obj) Returns count of how many times obj occurs in list list.extend(seq) Appends the contents of seq to list list.index(obj) Returns the lowest index in list that obj appears list.insert(index, obj) Inserts object obj into list at offset index list.pop(obj=list[-1]) Removes and returns last object or obj from list list.remove(obj) Removes object obj from list list.reverse() Reverses objects of list in place list.sort([func]) Sorts objects of list, use compare func if given

APPEND myList1 = [1,2,3] myList2 = [10,20,30] print myList1 myList1.append(myList2) #OUTPUT [1, 2, 3] [10, 20, 30] [1, 2, 3, [10, 20, 30]]

EXTEND myList1 = [1,2,3] myList2 = [10,20,30] print myList1 myList1.extend(myList2) #OUTPUT [1, 2, 3] [10, 20, 30] [1, 2, 3, 10, 20, 30]

Count example list1 = [1,1,1,2,2,3] print list1.count(1) Outputs 3 2 1

b=a (points to same list) a = list1 b = a print a print b a[0] = 9

b=a (points to same list) a = list1 b = a print a print b a[0] = 9 [0, 1, 2, 3] [9, 1, 2, 3] The difference is in bold

b = a[:] copy a list list1 = [0,1,2,3] a = list1 b = a[:] print a print b a[0] = 9

b = a[:] copy a list list1 = [0,1,2,3] a = list1 b = a[:] print a print b a[0] = 9 OUTPUT [0, 1, 2, 3] [9, 1, 2, 3] [0, 1, 2, 3] (notice this has not changed to 9)

Mutable Data Lists are mutable (can change) E.g. shoppingList[0] = “eggs” Will change the first item to “eggs”

Immutable Data A tuple does cannot change E.g. carRegistration = (2001, “X715KRW”,12112) These things typically do not change for a car (year of manufacture, Registration, chassis number) E.g. carRegistration = (2015, “JOHN 1”, 33452) You can reassign, if you buy a new car

Pre-computers Writing in pencil is like mutable data It can be erases and rewritten. Writing in ink is like immutable data Once is it written – you are stuck with it – like a Tattoo.

Tuples John R. Woodward

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 changed i.e., tuples are immutable tuples use parentheses and lists use square brackets. Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also. tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d";

Tuples 2 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,); ??? tup1 = (50);??? What would this mean Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.

Types - Be careful tup1 = (50,) print tup1 print type(tup1) tup1 = (50)#no comma

Types - Be careful Output: (50,) <type 'tuple'> 50 print tup1 print type(tup1) tup1 = (50)#no comma Output: (50,) <type 'tuple'> 50 <type 'int'>

Same with Strings tup1 = ("Stirling") print tup1 print type(tup1)

Same with Strings OUTPUT Stirling <type 'str'> ('Stirling',) tup1 = ("Stirling") print tup1 print type(tup1) tup1 = ("Stirling",) OUTPUT Stirling <type 'str'> ('Stirling',) <type 'tuple'>

Updating Tuples Tuples are immutable. You are able to take portions of existing tuples to create new tuples tup1 = (12, 34.56); tup2 = ('abc', 'xyz'); tup3 = tup1 + tup2; print tup3; it produces the following result: (12, 34.56, 'abc', 'xyz')

Delete Tuple Elements Removing individual tuple elements is not possible. There is nothing wrong with putting together another tuple with the desired elements. To explicitly remove an entire tuple, just use the del statement. tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After deleting tup : " print tup;#WHAT ERROR WOULD YOU GET

Basic Tuples Operations Python Expression Results Description len((1, 2, 3)) 3 Length (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition 3 in (1, 2, 3) 4 not in (1, 2, 3) True Membership for x in (1, 2, 3): print x, 1 2 3 Iteration

Indexing L = ('spam', 'Spam', 'SPAM!') Python Expression Results Description L[2] 'SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in Tuple Functions cmp(tuple1, tuple2) Compares elements of both tuples. len(tuple) Gives the total length of the tuple. max(tuple) Returns item from the tuple with max value. min(tuple) Returns item from the tuple with min value. tuple(seq) Converts a list into tuple.

Accessing Values in Tuples To access values in tuple, use the square brackets. tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0] print "tup2[1:5]: ", tup2[1:5] it produces the following result: tup1[0]: physics tup2[1:5]: [2, 3, 4, 5]

EXAMPLE integers = (0,1,2,3,4,5,6,7,8,9) print integers subset1 = integers[1:3] print subset1

EXAMPLE integers = (0,1,2,3,4,5,6,7,8,9) print integers subset1 = integers[1:3] print subset1 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) 1 9 (1, 2) OUTPUT

EXAMPLE subset1 = integers[1:8:2] print subset1

EXAMPLE output subset1 = integers[1:8:2] (1, 3, 5, 7) print subset1 () (8, 7, 6, 5) subset1 = integers[1:8:2] print subset1 subset1 = integers[8:1:2] subset1 = integers[8:4:-1] subset1 = integers[4:8:-1]