Chapter 7 : Lists, Tuples

Post on 09-Feb-2022

10 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Chapter 7 : Lists, Tuples

COSC 1436, Fall 2017

Hong Sun

11/1/2017

Chapter 6 review

• In Python, you don't need to import any library to read and write files. The first step is to get a file object. The way to do this is to use the open function.

• file_object = open(filename, mode)

• Mode can be ‘w’, ’r’ ,’a’

• file_object.close() – close file

Chapter 6 review

• File functions

• read(size) size is an optional numeric argument and this func returns a quantity of data equal to size. If size if omitted, then it reads the entire file and returns it

• readline() reads a single line from file with newline at the end

• readlines() returns a list containing all the lines in the file

Chapter 6 review

• Example

• file = open('newfile.txt', 'r') -- open a file

• file_content=file.read() -- return a string containing all characters in the file

• flie_list=file.readlines() -- returns a list containing all the lines in the file

Chapter 6 review

• Example

• Using loop to read lines

• while loop

• line = file.readline() ## get first line in file

• while line !=‘’:

• print(line)

• line = file.readline() ## read file line by line

Chapter 6 review

• Example • Using loop to read lines • for loop • for line in file: • print(line) • line = file.readline() ## read file line by line

• *** stripping new line • Line = line.rstrip(‘\n’)

• https://docs.python.org/2/library/datetime.html

Chapter 7 List and Tuple

• Sequences: A sequence is an object that contains multiple items of data. The items are in a sequence are stored one after the other.

• There are several different types of sequence object in Python.

• Two fundamental sequence type: Lists and Tuples.

• Both lists and tuples can hold various types of data. But list is mutable, tuple is immutable.

Lists

• A list is an object that contains multiple data items. Lists are mutable which means that their contents can be changed during a program’s execution. Lists are dynamic data structures, meaning that items may be added to them or removed from them. You can use indexing, slicing, and various methods to work with lists in a program.

2 4 6 8 10

Molly Steve Will Alica Adrew

Aiica 27 1150.87 true 1234

Create List

• Creating a list is as simple as putting different comma-separated values between square brackets. For example −

• list1 = ['physics', 'chemistry', 1997, 2000];

• list2 = [1, 2, 3, 4, 5 ];

• list3 = ["a", "b", "c", "d"]

Basic list operations

Python Expression Results Description

len([1, 2, 3]) 3 Length function

[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

The list operation

• list * n

Numbers=[0] * 5

Print(Numbers)

Output: [0,0,0,0,0]

Numbers = [1,2,3] * 3

Print(Numbers)

Output: [1,2,3,1,2,3,1,2,3]

List Basic Operators and functions - continue

• len function numbers=[99,100,101,102] length = len(numbers) print(length) index = 0 while index < len(numbers) print(numbers[index]) index += 1

• Lists are mutable numbers=[99,100,101,102] numbers[0] = 5 print(numbers)

output: [5,100,101,102]

List Basic Operators and functions - continue

• Concatenating lists list1=[1,2,3,4] list2=[5,6,7,8] list3=list1 + list2 Print(list3)

• In Operator Find items in List with the in Operator Item in List

• Code example sales_list.py (p296) in_list.py (p302)

Indexing, Slicing

Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero (index)

L[-2] 'Spam' Negative: count from the right (index)

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections (slicing)

Assuming following input − L = ['spam', 'Spam', 'SPAM!']

List functions - continue

• Indexing Index = 0 numbers=[99,100,101,102] While index < 4 print(numbers[index]) index += 1

• List Slicing – selects a range of element from a sequence list_name[start : end] months =[“January”, “February” , ”March”, “April”, “May”] #get items from indexes 1 up to but not including 4 mid_month= months [1: 4] print(mid_month) output: [February, March,April,May]

List Methods and Useful Built-in Function

• A few of the list methods

Method Description

append(item) Adds item to the end of the list

index(item) Returns the index of the first element whose value is equal to item. A ValueError exception is raised if item is not found in the list.

Insert(index , Item)

Inserts item into the list at the specified index. When an item is inserted into a list, the list is expanded in size to accommodate the new item. The item that was previously at the specified index, and all the items after it, are shifted by one position toward the end of the list. If you specify an index beyond the end of the list, the item will be added to the end of the list. If you use a negative index that specifies an invalid position, the item will be inserted at the beginning of the list

Sort() Sorts the items in the list so they appear in ascending order.

remove(item) Removes the first occurrence of item from the list. A ValueError exception is raised if item is not found in the list

Reverse() Reverses the order of the items in the list

del, min, max, copy functions

• del list_name[index] – del the value at the specified position in the list

del my_list[2]

• min list_name – Get the minimum value in the list

min (my_list)

• max list_name Max(my_list)

– Get the maximum value in the list

del, min, max, copy

• copy list list1 = [1,2,3,4,5] list2 = list1 Or list1 = [1,2,3,4,5] list2 = [] for item in list1: list2.append(item)

• Processing list Totaling the value in a list Averaging the value in a list code example: total_list.py, avarage_list.py (p314-315)

Work with functions and Files • Passing a List as an Argument to a Function and Returning a List from a

Function

• def main(): • # Create a list. • numbers = [2, 4, 6, 8, 10] • print('The total is', get_total(numbers))

• def get_total(value_list): • # Create a variable to use as an accumulator. • total = 0 • • # Calculate the total of the list elements. • for num in value_list: • total += num

• # Return the total. • return total

• # Call the main function. • main()

Work with functions and Files

• Passing a List as an Argument to a Function and Returning a List from a Function

Code example: total_function.py

return_list.py (p316)

• Working with Files Code example: writelines.py

Write_list.py

Read_list.py (p322)

Two-Dimensional Lists

• A two-dimensional list is a list that has other lists as its elements

• Access each of a two-dimensional list elements for r in range(rows):

for c in range(cols):

print(value[r][c])

Row 0 ‘Joe’ ‘Kim’

Row 1 ‘Sam’ ‘Sue’

Row 2 ‘Kelly’ ‘Chris’

Column0 Column1

Tuples

• A tuple is an immutable sequence, which means that its contents cannot be changed.

My_tuple = (1, 2, 3, 4,5) Names_tuple=(‘Holly’,’Warren’,’Ashley’) Print(My_tuple) Output: (1,2,3,4,5) for n in Names_tuple : print(n) For i in range(len(Names_tuple)): print(names[i])

Output: Holly Warren Ashley

• Converting between Lists and Tuples My_tuple=(1,2,3,4) My_list = list(My_tuple) MyList=[‘Holly’,’Warren’,’Ashley’] Mytuple=tuple(MyList)

Tuples

• Technically, mutability and the syntax are the only differences between lists and tuples in Python

• Lists are mutable and tuples are immutable

• Tuple support all the same operations as list, except those change the contents of the list.

Tuples

• Tuples don’t support methods such as append, insert, remove, reverse, sort

• Tuples support following :

subscript index (for retrieve element value only)

index function

len, min, max function

slicing expressing

the in operator

the + and * operators

Lab and assignment

• Lab: chapter 7: programming exercises: #1, #2, #6

• Assignment:

– Chapter 7: exercise #4, #7, #11

– Due date: 11/15/2017

top related