0% found this document useful (0 votes)
30 views52 pages

Chapter 07+08

İTÜ BIL100E notları

Uploaded by

erdemsimsek234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views52 pages

Chapter 07+08

İTÜ BIL100E notları

Uploaded by

erdemsimsek234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

CHAPTER 7

Lists and
Tuples

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Topics
Sequences
Introduction to Lists
List Slicing
Finding Items in Lists with the in
Operator
List Methods and Useful Built-in
Functions
Topics (cont’d.)

Copying Lists
Processing Lists
Two-Dimensional Lists
Tuples
Sequences
Sequence: an object that contains
multiple items of data
The items are stored in sequence one after
another
Python provides different types of
sequences, including lists and tuples
The difference between these is that a list is
mutable and a tuple is immutable
Introduction to Lists
 List: an object that contains multiple data
items
Element: An item in a list
Format: list = [item1, item2, etc.]
Can hold items of different types
 print function can be used to display an
entire list
 list() function can convert certain types of
objects to lists
Introduction to Lists (cont’d.)
The Repetition Operator and
Iterating over a List
 Repetition operator: makes multiple copies
of a list and joins them together
The * symbol is a repetition operator when
applied to a sequence and an integer
Sequence is left operand, number is right
General format: list * n
 You can iterate over a list using a for loop
Format: for x in list:
Indexing
Index: a number specifying the position
of an element in a list
Enables access to individual element in list
Index of first element in the list is 0, second
element is 1, and n’th element is n-1
Negative indexes identify positions relative to
the end of the list
The index -1 identifies the last element, -2
identifies the next to last element, etc.
The len function

An IndexError exception is raised if


an invalid index is used
len function: returns the length of a
sequence such as a list
Example: size = len(my_list)
Returns the number of elements in the list, so
the index of last element is len(list)-1
Can be used to prevent an IndexError
exception when iterating over a list with a loop
Lists Are Mutable
 Mutable sequence: the items in the sequence
can be changed
Lists are mutable, and so their elements can
be changed
 An expression such as
 list[1] = new_value can be used to
assign a new value to a list element
Must use a valid index to prevent raising of an
IndexError exception
Concatenating Lists
Concatenate: join two things together
The + operator can be used to
concatenate two lists
Cannot concatenate a list with another data
type, such as a number
The += augmented assignment
operator can also be used to
concatenate lists
List Slicing
Slice: a span of items that are taken
from a sequence
List slicing format: list[start : end]
Span is a list containing copies of elements
from start up to, but not including, end
If start not specified, 0 is used for start index
If end not specified, len(list) is used for end
index
Slicing expressions can include a step value
and negative indexes relative to end of list
Finding Items in Lists with
the in Operator
 You can use the in operator Bookex7_1.py
to determine whether an
# This program demonstrates the in operator
item is contained in a list # used with a list.

 General format: item in def main():


# Create a list of product numbers.
list prod_nums = ['V475', 'F987', 'Q143', 'R688']
 Returns True if the item is # Get a product number to search for.
in the list, or False if it is search = input('Enter a product number: ')

not in the list # Determine whether the product number is in the


# list.
 Similarly you can use the if search in prod_nums:
print(search, 'was found in the list.')
not in operator to else:
determine whether an item print(search, 'was not found in the list.')

is not in a list # Call the main function.


main()
List Methods and Useful Built-in
Functions
append(item): used to add items to a
list – item is appended to the end of
the existing list
index(item): used to determine
where an item is located in a list
Returns the index of the first element in the
list containing item
Raises ValueError exception if item not in
the list
List Methods and Useful Built-in
Functions (cont’d.)
 insert(index, item): used to insert item
at position index in the list
 sort(): used to sort the elements of the list
in ascending order
 remove(item): removes the first occurrence
of item in the list
 reverse(): reverses the order of the
elements in the list
Bookex7_2.py

# This program demonstrates how the append


# method can be used to add items to a list.

def main():
# First, create an empty list.
name_list = []

# Create a variable to control the loop.


again = 'y'

# Add some names to the list.


while again == 'y':
# Get a name from the user.
name = input('Enter a name: ')

# Append the name to the list.


name_list.append(name)

...

for name in name_list:


print(name)

# Call the main function.


main()
List Methods and Useful Built-in
Functions (cont’d.)
 del statement: removes an element from a
specific index in a list
General format: del list[i]

 min and max functions: built-in functions


that returns the item that has the lowest or
highest value in a sequence
The sequence is passed as an argument
Copying Lists

To make a copy of a list you must copy


each element of the list
Two methods to do this:
Creating a new empty list and using a for loop to
add a copy of each element from the original list to
the new list
Creating a new empty list and concatenating the
old list to the new empty list
Copying Lists (cont’d.)
Processing Lists

 List elements can be used in calculations


 To calculate total of numeric values in a list
use loop with accumulator variable
 To average numeric values in a list:
Calculate total of the values
Divide total of the values by len(list)
 List can be passed as an argument to a
function
Processing Lists (cont’d.)

 A function can return a reference to a list


 To save the contents of a list to a file:
Use the file object’s writelines method
Does not automatically write \n at then end of
each item
Use a for loop to write each element and \n
 To read data from a file use the file object’s
readlines method
Two-Dimensional Lists

 Two-dimensional list: a list that contains


other lists as its elements
Also known as nested list
Common to think of two-dimensional lists as
having rows and columns
Useful for working with multiple sets of data
 To process data in a two-dimensional list
need to use two indexes
 Typically use nested loops to process
Two-Dimensional Lists
(cont’d.)
Bookex7_3.py

# This program assigns random numbers to


# a two-dimensional list.
import random

# Constants for rows and columns


ROWS = 3
COLS = 4

def main():
# Create a two-dimensional list.
values = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]

# Fill the list with random numbers.


for r in range(ROWS):
for c in range(COLS):
values[r][c] = random.randint(1, 100)

# Display the random numbers.


print(values)

# Call the main function.


main()
Two-Dimensional Lists
(cont’d.)
Tuples
Tuple: an immutable sequence
Very similar to a list
Once it is created it cannot be changed
Format: tuple_name = (item1, item2)
Tuples support operations as lists
Subscript indexing for retrieving elements
Methods such as index
Built in functions such as len, min, max
Slicing expressions
The in, +, and * operators
Tuples (cont’d.)

Tuples do not support the methods:


append
remove
insert
reverse
sort
Tuples (cont’d.)

Advantages for using tuples over lists:


Processing tuples is faster than processing
lists
Tuples are safe
Some operations in Python require use of
tuples
list() function: converts tuple to list
tuple() function: converts list to tuple
Summary
 This chapter covered:
 Lists, including:
 Repetition and concatenation operators
 Indexing
 Techniques for processing lists
 Slicing and copying lists
 List methods and built-in functions for lists
 Two-dimensional lists
 Tuples, including:
 Immutability
 Difference from and advantages over lists
CHAPTER 8
More About
Strings

Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley


Topics

Basic String Operations


String Slicing
Testing, Searching, and Manipulating
Strings
Basic String Operations

Many types of programs perform


operations on strings
In Python, many tools for examining
and manipulating strings
Strings are sequences, so many of the tools
that work with sequences work with strings
Accessing the Individual
Characters in a String
 To access an individual character in a string:
Use a for loop
Format: for character in string:
Useful when need to iterate over the whole string,
such as to count the occurrences of a specific
character
Use indexing
Each character has an index specifying its position
in the string, starting at 0
Format: character = my_string[i]
Bookex8_1.py

# This program counts the number of times


# the letter T (uppercase or lowercase)
# appears in a string.

def main():
# Create a variable to use to hold the count.
# The variable must start with 0.
count = 0

# Get a string from the user.


my_string = input('Enter a sentence: ')

# Count the Ts.


for ch in my_string:
if ch == 'T' or ch == 't':
count += 1

# Print the result.


print('The letter T appears', count, 'times.')

# Call the main function.


main()
Accessing the Individual
Characters in a String (cont’d.)
Accessing the Individual
Characters in a String (cont’d.)
IndexError exception will occur if:
You try to use an index that is out of range for
the string
Likely to happen when loop iterates beyond the
end of the string
len(string) function can be used to
obtain the length of a string
Useful to prevent loops from iterating beyond
the end of a string
String Concatenation
 Concatenation: appending one
string to the end of another
string Bookex8_2.py
 Use the + operator to produce
# This program concatenates strings.
a string that is a combination of
its operands def main():
name = 'Carmen‘
 The augmented assignment print('The name is', name)
name = name + ' Brown'
operator += can also be used print('Now the name is', name)
to concatenate strings
# Call the main function.
The operand on the left side main()
of the += operator must be
an existing variable;
otherwise, an exception is
raised
Strings Are Immutable

Strings are immutable


Once they are created, they cannot be
changed
Concatenation doesn’t actually change the existing
string, but rather creates a new string and assigns
the new string to the previously used variable
Cannot use an expression of the form
 string[index] = new_character
Statement of this type will raise an exception
Strings Are Immutable
(cont’d.)
String Slicing
Slice: span of items taken from a
sequence, known as substring
Slicing format: string[start : end]
Expression will return a string containing a copy of
the characters from start up to, but not including,
end
If start not specified, 0 is used for start index
If end not specified, len(string) is used for end
index
Slicing expressions can include a step value
and negative indexes relative to end of string
Testing, Searching, and
Manipulating Strings
 You can use the in operator to determine
whether one string is contained in another
string
General format: string1 in string2
string1 and string2 can be string literals or
variables referencing strings
 Similarly you can use the not in operator to
determine whether one string is not
contained in another string
String Methods
 Strings in Python have many types of
methods, divided into different types of
operations
General format:
mystring.method(arguments)
 Some methods test a string for specific
characteristics
Generally Boolean methods, that return True
if a condition exists, and False otherwise
String Methods (cont’d.)
String Methods (cont’d.)
Bookex8_3.py

# This program demonstrates several string testing methods.


def main():
# Get a string from the user.
user_string = input('Enter a string: ')

print('This is what I found about that string:')

# Test the string.


if user_string.isalnum():
print('The string is alphanumeric.')
if user_string.isdigit():
print('The string contains only digits.')
if user_string.isalpha():
print('The string contains only alphabetic characters.')
if user_string.isspace():
print('The string contains only whitespace characters.')
if user_string.islower():
print('The letters in the string are all lowercase.')
if user_string.isupper():
print('The letters in the string are all uppercase.')

# Call the string.


main()
String Methods (cont’d.)
String Methods (cont’d.)

 Some methods return a copy of the string, to


which modifications have been made
Simulate strings as mutable objects
 String comparisons are case-sensitive
Uppercase characters are distinguished from
lowercase characters
lower and upper methods can be used for
making case-insensitive string comparisons
String Methods (cont’d.)
String Methods (cont’d.)
Programs commonly need to search for
substrings
Several methods to accomplish this:
endswith(substring): checks if the string
ends with substring
Returns True or False
startswith(substring): checks if the
string starts with substring
Returns True or False
String Methods (cont’d.)
Several methods to accomplish this
(cont’d):
find(substring): searches for
substring within the string
Returns lowest index of the substring, or if the
substring is not contained in the string, returns -1
replace(substring, new_string):
Returns a copy of the string where every
occurrence of substring is replaced with
new_string
String Methods (cont’d.)
The Repetition Operator
 Repetition operator: makes
multiple copies of a string
and joins them together Bookex8_4.py
 The * symbol is a # This program demonstrates the repetition
repetition operator when # operator.

applied to a string and an def main():


integer # Print nine rows increasing in length.
for count in range(1, 10):
 String is left operand; print('Z' * count)
number is right
# Print nine rows decreasing in length.
 General format: for count in range(8, 0, -1):
string_to_copy * n print('Z' * count)

 Variable references a new # Call the main function.


main()
string which contains
multiple copies of the
original string
Splitting a String
split method:
returns a list Bookex8_5.py

containing the # This program demonstrates the split


method.
words in the string def main():
# Create a string with multiple words.
By default, uses my_string = 'One two three four'

space as separator # Split the string.


word_list = my_string.split()
Can specify a # Print the list of words.
different separator by print(word_list)

passing it as an # Call the main function.


main()
argument to the
split method
Summary
This chapter covered:
String operations, including:
Methods for iterating over strings
Repetition and concatenation operators
Strings as immutable objects
Slicing strings and testing strings
String methods
Splitting a string

You might also like