Podcast
Questions and Answers
What does the sort method do to a list?
What does the sort method do to a list?
What is the result of calling a mutator method like sort on a list?
What is the result of calling a mutator method like sort on a list?
What occurs when two variables point to the same list object?
What occurs when two variables point to the same list object?
What should you do to prevent aliasing when copying a list?
What should you do to prevent aliasing when copying a list?
Signup and view all the answers
Which of the following statements about the sort method is correct?
Which of the following statements about the sort method is correct?
Signup and view all the answers
What does the == operator indicate when comparing two variables in Python?
What does the == operator indicate when comparing two variables in Python?
Signup and view all the answers
Which operator in Python is specifically used to test for object identity?
Which operator in Python is specifically used to test for object identity?
Signup and view all the answers
Based on the example provided, what will be the result of comparing 'first' and 'third' using the is operator?
Based on the example provided, what will be the result of comparing 'first' and 'third' using the is operator?
Signup and view all the answers
When determining the median of a set of numbers, which of the following is a necessary step?
When determining the median of a set of numbers, which of the following is a necessary step?
Signup and view all the answers
What can be inferred about the relations checked by the == and is operators in Python?
What can be inferred about the relations checked by the == and is operators in Python?
Signup and view all the answers
What allows a programmer to manipulate a sequence of data values of any type?
What allows a programmer to manipulate a sequence of data values of any type?
Signup and view all the answers
What is the primary structural difference between a list and a dictionary?
What is the primary structural difference between a list and a dictionary?
Signup and view all the answers
Which operation is not typically associated with lists?
Which operation is not typically associated with lists?
Signup and view all the answers
In which scenario would a dictionary be more appropriate than a list?
In which scenario would a dictionary be more appropriate than a list?
Signup and view all the answers
What might be a consequence of using a list in a situation requiring key-value pairs?
What might be a consequence of using a list in a situation requiring key-value pairs?
Signup and view all the answers
What does the is operator check in Python?
What does the is operator check in Python?
Signup and view all the answers
What will the expression 'first == second' evaluate to in the provided example?
What will the expression 'first == second' evaluate to in the provided example?
Signup and view all the answers
What is indicated when 'first is third' evaluates to False?
What is indicated when 'first is third' evaluates to False?
Signup and view all the answers
Why can the == operator be ambiguous when comparing two objects?
Why can the == operator be ambiguous when comparing two objects?
Signup and view all the answers
What is the purpose of using a list in finding the median of a set of numbers?
What is the purpose of using a list in finding the median of a set of numbers?
Signup and view all the answers
What does the expression '3 in [1, 2, 3]' evaluate to?
What does the expression '3 in [1, 2, 3]' evaluate to?
Signup and view all the answers
How can you replace the first element of the list 'example = [1, 2, 3, 4]' with the value 0?
How can you replace the first element of the list 'example = [1, 2, 3, 4]' with the value 0?
Signup and view all the answers
What will the list 'numbers' contain after executing the loop with 'numbers = [2, 3, 4, 5]'?
What will the list 'numbers' contain after executing the loop with 'numbers = [2, 3, 4, 5]'?
Signup and view all the answers
What does the method 'split()' do when called on a string?
What does the method 'split()' do when called on a string?
Signup and view all the answers
After executing 'words[index] = words[index].upper()' on the list of words extracted from the sentence, what will 'words' contain?
After executing 'words[index] = words[index].upper()' on the list of words extracted from the sentence, what will 'words' contain?
Signup and view all the answers
What does the method L.append(element) accomplish?
What does the method L.append(element) accomplish?
Signup and view all the answers
What happens when you use L.insert(index, element) with an index greater than the length of L?
What happens when you use L.insert(index, element) with an index greater than the length of L?
Signup and view all the answers
What is the purpose of the method L.extend(aList)?
What is the purpose of the method L.extend(aList)?
Signup and view all the answers
What does the method L.pop(index) return?
What does the method L.pop(index) return?
Signup and view all the answers
Given the example list [1, 2], what will the list be after example.insert(1, 10)?
Given the example list [1, 2], what will the list be after example.insert(1, 10)?
Signup and view all the answers
Study Notes
Fundamentals of Python: First Programs - Second Edition
- This is a Python programming textbook, second edition
- Chapter 5 focuses on lists and dictionaries
Chapter 5: Lists and Dictionaries
-
Objectives (Part 1 of 2):
- Construct lists and access items
- Use methods to manipulate lists
- Perform traversals of lists
- Define simple functions expecting parameters and returning values
-
Objectives (Part 2 of 2):
- Construct dictionaries and access entries
- Use methods to manipulate dictionaries
- Determine whether a list or a dictionary is appropriate for a given application
Introduction
- Lists manipulate sequences of any data type
- Dictionaries organize data values by association rather than sequential position
- Lists and dictionaries efficiently organize data for applications
Lists
- Lists are ordered sequences of items (elements)
- Examples include shopping lists, to-do lists, rosters, guest lists, recipes, text documents, and phone books
- Each list item has a unique index (position from 0 to length - 1)
List Literals and Basic Operators (Part 1 of 4)
- Examples of list literals include: ['apples', 'oranges', 'cherries'], [[5, 9], [541, 78]]
- Elements within a list can be expressions, whose values are calculated and included in the list
- Example: [x, math.sqrt(x)] where x = 2 results in [2, 1.4142135623730951]
List Literals and Basic Operators (Part 2 of 4)
- Building lists of integers using the range function
- Example, first =[1, 2, 3, 4] and second = list(range(1, 5)) both result in the same list [1,2,3,4]
- The list function creates a list from an iterable sequence of elements
- Example, list("Hi there!" results in ['H', 'i', '', 't', 'h', 'e', 'r', 'e', '!']
List Literals and Basic Operators (Part 3 of 4)
- The len function, square brackets, the plus sign (+), and the equals sign (==) operate on lists as expected
- Example of list concatenation (using +): first + [5, 6] results in [1, 2, 3, 4, 5, 6]
- Example of list equality (using ==): first == second results in True
List Literals and Basic Operators (Part 4 of 4)
- Printing list contents:
- Example, print(“1234”) will print "1234"; print([1, 2, 3, 4]) will print [1, 2, 3, 4]
- Using the in operator to check for an element:
- Example, 3 in [1, 2, 3] returns True; 0 in [1, 2, 3] returns False
Replacing an Element in a List (Part 1 of 2)
- Lists are mutable. Elements can be inserted, removed, or replaced
- Contents of a list can change but its identity remains the same.
- Using the subscript operator to replace an element:
- Example, example = [1, 2, 3, 4] --> example[3] = 0 --> example = [1, 2, 3, 0]
Replacing an Element in a List (Part 2 of 2)
- Replacing elements in a list based on an index and using string method .split()
- Examples, [2,3,4,5] to [4,9,16,25]; and “This example has five words.” to ["THIS", "EXAMPLE", "HAS", "FIVE", "WORDS."]
List Methods for Inserting and Removing Elements (Part 1 of 4)
- Summary table of list methods explaining the effect of each method on the list
List Methods for Inserting and Removing Elements (Part 2 of 4)
- Method insert to insert an integer index and a new element. Example adding 10 in index 1 results in [1,10,2]
List Methods for Inserting and Removing Elements (Part 3 of 4)
- Method append to add a new element to the end of the list
- Method extend to add the elements from another list to the end of a list
List Methods for Inserting and Removing Elements (Part 4 of 4)
- Method pop to remove an element
- Example removing last element from [1, 2, 10, 11, 12,13] results in [1, 2, 10, 11, 12]; removing the first results in [10, 11, 12]
Searching a List
- The in operator determines if an element exists in a list.
- Method index locates an element's position. Raises an error if the element is not found
- Example: aList = [34, 45, 67], target = 45, if target in aList: print(aList.index(target)) else: print(-1)
Sorting a List
- List elements are ordered by position; can be sorted alphabetically
- Method sort rearranges list elements in ascending order. Example: example = [4, 2, 10, 8] -> example.sort() -> example = [2, 4, 8, 10]
Mutator Methods and the Value None
- Mutator methods (insert, append, extend, pop, and sort) change a list
- Python returns None after the mutator methods are executed
Aliasing and Side Effects (Part 1 of 2)
- Lists have a mutable property: aliasing can lead to unexpected results
- Two variables (first and second), referencing the same list object. Changing one affects the other example, [1,2,3] -> [1,99,3] which also changes the second variable holding the same data.
Aliasing and Side Effects (Part 2 of 2)
- Creating a new object to prevent aliasing, copying the contents of one list object to a new list object.
- Example third = [] for element in first: third.append(element) changes values independent in variables.
Equality: Object Identity and Structural Equivalence (Part 1 of 2)
- Programmers determine whether variables refer to the same object or different objects
- == operator returns true if variables are aliases
- == returns true if values are identical
- The issue with the == operator is its inability to distinguish between type of equivalence.
Equality: Object Identity and Structural Equivalence (Part 2 of 2)
- Use the is operator for testing object identity
- Example: first = [20, 30, 40]; second = first; third = list(first); first == second returns true; first == third returns true; first is second returns true; first is third returns false.
Example: Using a List to Find the Median of a Set of Numbers
- Python code to find the median of a list of numbers
Tuples
- Tuples are similar to lists but immutable, indicated by enclosing elements in parenthesis -Example: fruits = (“apple”, “banana”)
Defining Simple Functions
- Defining functions helps organize code effectively in Python programs
- Section provides an overview of how to define Python functions
The Syntax of Simple Function Definitions
- Function definitions consist of header and body
- Example function: def square(x): """Returns the square of x.""" return x * x
- To view help, use help(square)
Parameters and Arguments
- Parameters are names used in function definitions
- Arguments are values passed to functions when called
- Functions expect arguments matching parameter structure
The Return Statement
- The return statement specifies value(s) function returns
- A function without a return statement returns None
Boolean Functions
- Boolean functions test arguments for properties
- Example: def odd(x): if x % 2 == 1: return True; else: return False
Defining a Main Function (Part 1 of 2)
- Main serves as the entry point for a Python script
- Typically has no arguments and returns no values; can have definition before other functions
- Code can be run in IDLE, imported into the shell, or run from a terminal command prompt
Defining a Main Function (Part 2 of 2)
- Example of a main function in Python code
Dictionaries
- Dictionaries organize information by association
- Keys map unique data values
- Example a phone book with names and numbers; personal information with name, age
Dictionary Literals
- Python dictionaries use key-value pairs enclosed in curly brackets {}
- Keys are associated with data values. Example a phone book with names as key and number as value
Adding Keys and Replacing Values
- Using square brackets [] adds new key-value pairs or replaces existing values.
- Example: info = {}; info[“name”] = “Sandy”; info[“occupation”] = “hacker”
Accessing Values (Part 1 of 2)
- Use square brackets [] to access dictionary values associated with keys
- Raises an error if the key is not found example: Trying to get info["job"] when the key "job" was not defined
Accessing Values (Part 2 of 2)
- Use the has_key method to test whether a key exists.
- The get() method returns a default value if a key is not found
Removing Keys
- Delete entries from dictionaries using the pop method
- Example: print(info.pop(“occupation”))
Traversing a Dictionary (Part 1 of 3)
- Print all keys and values: for key in info: print(key, info[key])
- Alternative, using the items() method. Example: grades = {90:'A', 80:'B', 70:'C'}; list(grades.items()) , which results in tuples [(80, 'B'),(90, 'A'),( 70, 'C')]
Traversing a Dictionary (Part 2 of 3)
- Sorting the list of keys from the dictionary example print all keys and values in alphabetical order: theKeys = list(info.keys()); theKeys.sort() for key in theKeys: print(key, info[key]).
Traversing a Dictionary (Part 3 of 3)
- Summary table of dictionary operations (len, [], get, pop, keys(), values(), items(), clear)
Chapter Summary (Part 1 of 2)
- Recap of list properties (sequence of elements, mutable, indexable, concatenation, comparison, in operator
- How lists and sort methods work.
- Mutator methods change the state of an object.
Chapter Summary (Part 2 of 2)
- Recap of tuples
- Syntax of function definitions, return statements
- Definition of dictionaries and use of square brackets []
- How testing can be done (bottom-up, top-down, or mixed approach)
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.
Related Documents
Description
Test your knowledge on Python list methods and comparison operators with this quiz. You will explore the workings of the sort method, mutator methods, and the differences between the == and is operators. Understand how list aliasing affects variable references and how to properly manage list copying.