CSC 121 Lists and Tuples

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

This program creates a list of popular programming/scripting languages. Fill in the missing line for the first insert statement. Expected Output The list before the insert: ['Python', 'Java', 'R'] The list after the insert: ['Python', 'Java', 'c', 'R'] The list after another insert: ['Python', 'Java', 'c', 'R', 'Javascript']

# This program demonstrates the insert method. def main(): ---> # Create a list with some programming languages. ---> languages = ['Python', 'Java', 'R'] ---> # Display the list. ---> print('The list before the insert:') ---> print(languages) ---> # Insert a new element. ---> languages.insert(2, 'c') ---> # Display the list again. ---> print('The list after the insert:') ---> print(languages) ---> # Insert a new element. ---> languages.insert(5, 'Javascript') ---> # Display the list again. ---> print('The list after another insert:') ---> print(languages) # Call the main function. main()

What will the following code display? numbers = list(range(1, 10, 2)) for n in numbers: ----> print(n)

1 3 5 7 9

After this code executes, what value will the list2 list hold? list1 = [1, 12, 2, 20, 3, 15, 4] list2 = [n for n in list1 if n > 10]

12 20 15

What will be displayed after the following code is executed? def pass_it(x, y): ---> z = x*y ---> result = get_result(z) ---> return(result) def get_result(number): ---> z = number + 2 ---> return(z) num1 = 3 num2 = 4 answer = pass_it(num1, num2) print(answer)

14

After this code executes, what value will the list2 list hold? list1 = [1, 12, 2, 20, 3, 15, 4] list2 = [n*2 for n in list1]

2 24 4 40 6 30 8

What will the following code display? numbers = [1, 2, 3, 4, 5] print(numbers[−2])

4

A two-dimensional list is created, as shown below. How many rows and how many columns are in the list? numbers = [[1, 2], [10, 20], [100, 200], [1000, 2000]]

4 rows and 2 columns

Returning a List from a Function

A function can return a reference to a list. This gives you the ability to write a function that creates a list and adds elements to it, then returns a reference to the list so other parts of the program can work with it.

Copying Lists Suppose you wish to make a copy of a list, so list1 and list2 reference two separate but identical lists. One way to do this is with a loop that copies each element of the list. Here is an example: # Create a list with values. list1 = [1, 2, 3, 4] # Create an empty list. list2 = [] # Copy the elements of list1 to list2. for item in list1: ---> list2.append(item)

After this code executes, list1 and list2 will reference two separate but identical lists. A simpler and more elegant way to accomplish the same task is to use the concatenation operator, as shown here: # Create a list with values. list1 = [1, 2, 3, 4] # Create a copy of list1. list2 = [] + list1 The last statement in this code concatenates an empty list with list1 and assigns the resulting list to list2. As a result, list1 and list2 will reference two separate but identical lists.

Indexing Error

An IndexError exception will be raised if you use an invalid index with a list. For example, look at the following code: # This code will cause an IndexError exception. my_list = [10, 20, 30, 40] index = 0 while index < 5: ----> print(my_list[index]) -----> index += 1 The last time that this loop begins an iteration, the index variable will be assigned the value 4, which is an invalid index for the list. As a result, the statement that calls the print function will cause an IndexError exception to be raised.

List Slicing Slice is a span of items that are taken from a sequence. When you take a slice from a list, you get a span of elements from within the list. To get a slice of a list, you write an expression in the following general format list_name[start : end] In the general format, start is the index of the first element in the slice, and end is the index marking the end of the slice. The expression returns a list containing a copy of the elements from start up to (but not including) end. days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] The following statement uses a slicing expression to get the elements from indexes 2 up to, but not including, 5: mid_days = days[2:5] After this statement executes, the mid_days variable references the following list: ['Tuesday', 'Wednesday', 'Thursday'] ____________________________________________________________________________________________ If you leave out the start index in a slicing expression, Python uses 0 as the starting index: print (name[:2] ['Chris', 'Megan',] If you leave out the end index in a slicing expression, Python uses the length of the list as the end index print (name[2:] ['Sally', 'James'] If you leave out both the start and end index in a slicing expression, you get a copy of the entire list print(name[:] ['Chris', 'Megan', 'Sally', 'James'] names = ['Chris', 'Megan', 'Sally', 'James'] n2 = names[1:3] ['Megan', 'Sally'] print (names[0:2]) ['Chris', 'Megan',]

Ex3: letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print (letters[2:5]) [ 'c', 'd', 'e'] Slicing expressions can also have step value, which can cause elements to be skipped in the list print(letters[::3] ['a', 'd', 'g'] You can also use negative numbers as indexes in slicing expressions to reference positions relative to the end of the list. Python adds a negative index to the length of a list to get the position referenced by that index print(letters[-3] ['e'] print (letters[-3:]) ['e', 'f', 'g'] ALLOWS ERROR TO OCCUR print(letters[0:7:2] ['a', 'c', 'e', 'g'] print(letters[0:7:3] ['a', 'd', 'g'] NOTE: Invalid indexes do not cause slicing expressions to raise an exception. If the end index specifies a position beyond the end of the list, Python will use the length of the list instead. If the start index specifies a position before the beginning of the list, Python will use 0 instead. If the start index is greater than the end index, the slicing expression will return an empty list.

A list cannot be passed as an argument to a function. https://www.w3schools.com/python/gloss_python_function_passing_list.asp

False

A python list is immutable

False

A sequence contains exactly two items of data.

False

The del method searches for and removes an element containing a specific value.

False

The remove method removes all occurrences of an item from a list.

False Only the first occurence

list() function convert certain types of objects to lists

For example, recall that the range function returns an iterable, which is an object that holds a series of values that can be iterated over. You can use a statement such as the following to convert the range function's iterable object to a list: numbers = list(range(5)) When this statement executes, the following things happen: 1) The range function is called with 5 passed as an argument. The function returns an iterable containing the values 0, 1, 2, 3, 4. 2) The iterable is passed as an argument to the list() function. 3) The list() function returns the list [0, 1, 2, 3, 4]. The list [0, 1, 2, 3, 4] is assigned to the numbers variable. EX2: numbers = list(range(1, 10, 2)) when you pass three arguments to the range function, the first argument is the starting value, the second argument is the ending limit, and the third argument is the step value. This statement will assign the list [1, 3, 5, 7, 9] to the numbers variable.

Indexing Another way that you can access the individual elements in a list is with an index. Each element in a list has an index that specifies its position in the list. Indexing starts at 0, so the index of the first element is 0, the index of the second element is 1, and so forth. The index of the last element in a list is 1 less than the number of elements in the list.

For example, the following statement creates a list with 4 elements: my_list = [10, 20, 30, 40] The indexes of the elements in this list are 0, 1, 2, and 3. We can print the elements of the list with the following statement: print(my_list[0], my_list[1], my_list[2], my_list[3]) The following loop also prints the elements of the list: index = 0 while index < 4: ----> print(my_list[index]) ----> index += 1

What will be the output after the following code is executed? def pass_it(x, y): ---> z = x + ", " + y ---> return(z) name2 = "Tony" name1 = "Gaddis" fullname = pass_it(name1, name2) print(fullname)

Gaddis, Tony

What will the following code display? names = ['Jim', 'Jill', 'John', 'Jasmine'] if 'Jasmine' not in names: ---> print('Cannot find Jasmine.') else: ---> print("Jasmine's family:") print(names)

Jasmine's family: ['Jim', 'Jill', 'John', 'Jasmine']

This program creates a two dimensional list to store popular songs (the rows) and their artists (the columns). Type the code into the interface below and where indicated, fill in the two nested loop statements and the print statement to display the expected output. Expected Output Bohemian Rhapsody Queen Stairway to Heaven Zeppelin Imagine Lennon Hotel California Eagles Sounds of Silence Simon and Garfunkel

Look at pycharm for code

The index Method

Sometimes you need to know not only whether an item is in a list, but where it is located. The index method is useful in these cases. You pass an argument to the index method, and it returns the index of the first element in the list containing that item. If the item is not found in the list, the method raises a ValueError exception.

List comprehension a concise expression that creates a new list by iterating over the elements of an existing list. [result_expression iteration_expression] An expression that reads an input list, using the values of the input list to produce an output list. For example, the previously shown code can be written using a list comprehension as follows: list1 = [1, 2, 3, 4] list2 = [item for item in list1] The list comprehension expression appears in the second line of code, enclosed in brackets. The list comprehension begins with a result expression, followed by an iteration expression. The iteration expression works like a for loop. Each time it iterates, the target variable item is assigned the value of an element. At the end of each iteration, the value of the result expression is appended to the new list. Suppose you have a list of strings, and you want to create a second list that contains the lengths of all the strings in the first list. The following code shows how to accomplish this using a for loop: str_list = ['Winken', 'Blinken', 'Nod'] len_list = [] for s in str_list: ---> len_list.append(len(s)) The following code shows how the same operation can be performed with a list comprehension: str_list = ['Winken', 'Blinken', 'Nod'] len_list = [len(s) for s in str_list] In the list comprehension, the iteration expression is for s in str_list and the result expression is len(s). After this code executes, len_list will contain the values [6, 7, 3].

Suppose you have a list of numbers and you want to create a second list that contains the squares of all the numbers in the first list. The following code shows how to accomplish this using a for loop: list1 = [1, 2, 3, 4] list2 = [] for item in list1: ---> list2.append(item**2) The following code shows how the same operation can be performed with a list comprehension: list1 = [1, 2, 3, 4] list2 = [item**2 for item in list1] Each time the iteration expression iterates, the target variable item is assigned the value of an element. At the end of each iteration, the value of the result expression item**2 is appended to list2. After this code executes, list2 will contain the values [1, 4, 9, 16].

Averaging the Values in a List

The first step in calculating the average of the values in a list is to get the total of the value.

using if Clauses with List Comprehensions [result_expression iteration_expression if_clause] Sometimes you want to select only certain elements when processing a list. For example, suppose a list contains integers and you want to make a second list that contains only the integers from the first list that are less than 10. The following code accomplishes that with a loop: list1 = [1, 12, 2, 20, 3, 15, 4] list2 = [] for n in list1: ---> if n < 10: -----> list2.append(n) The if statement that appears inside the for loop causes this code to append only the elements that are less than 10 to list2. After this code executes, list2 will contain [1, 2, 3, 4]. This type of operation can also be accomplished by adding an if clause to a list comprehension.

The if clause acts as a filter, allowing you to select certain items from the input list. The following code shows how we can rewrite the previous code using a list comprehension with an if clause: list1 = [1, 12, 2, 20, 3, 15, 4] list2 = [item for item in list1 if item < 10] In the list comprehension, the iteration expression is for item in list1, the if clause is if item < 10, and the result expression is item. After this code executes, list2 will contain [1, 2, 3, 4]. last_names = ['Jackson', 'Smith', 'Hildebrandt', 'Jones'] short_names = [name for name in last_names if len(name) < 6] The list comprehension, which iterates over the last_names list, has an if clause that selects only the elements that are less than 6 characters long. After this code executes, short_names will contain ['Smith', 'Jones']

Invalid indexes do not cause slicing expressions to raise an exception.

True

Once a Python tuple is created, its contents cannot be changed.

True

The index -1 identifies the last element in a list.

True

The items that are in a sequence are stored one after the other.

True

What is the best way to find the lowest and highest values in a list?

Use the built-in min and max functions

What is the best way to find the number of elements in a list?

Use the len function

Two-Dimensional Lists (nested lists) a list that contains other lists as its elements It is common to think of a two-dimensional list as having rows and columns of elements, as shown in Figure 7-5. This figure shows the two-dimensional list that was created in the previous interactive session as having three rows and two columns. Notice the rows are numbered 0, 1, and 2, and the columns are numbered 0 and 1. There is a total of six elements in the list It is common to think of a two-dimensional list as having rows and columns of elements, as shown in Figure 7-5. This figure shows the two-dimensional list that was created in the previous interactive session as having three rows and two columns. Notice the rows are numbered 0, 1, and 2, and the columns are numbered 0 and 1. There is a total of six elements in the list Programs that process two-dimensional lists typically do so with nested loops. Suppose we do not like the way that the print function displays the list enclosed in brackets, with each nested list also enclosed in brackets. For example, suppose we want to display each list element on a line by itself, like this: 4 For example, suppose we want to display each list element on a line by itself, like this: 4 17 34 24 46 Rather than: [[4, 17], [34, 24], [46]] for r in range(ROWS): ---> for c in range(COLS): -----> print(values[r][c])

When processing the data in a two-dimensional list, you need two subscripts: one for the rows, and one for the columns. For example, suppose we create a two-dimensional list with the following statement: scores = [[0, 0, 0], --------> [0, 0, 0], --------> [0, 0, 0]] The elements in row 0 are referenced as follows: scores[0][0] scores[0][1] scores[0][2] The elements in row 1 are referenced as follows: scores[1][0] scores[1][1] scores[1][2] And, the elements in row 2 are referenced as follows: scores[2][0] scores[2][1] scores[2][2]

Concatenating Lists Use the + operator to concatenate two lists NOTE: You can concatenate lists only with other lists. If you try to concatenate a list with something that is not a list, an exception will be raised. list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list3 = list1 + list2 After this code executes, list1 and list2 remain unchanged, and list3 references the following list: [1, 2, 3, 4, 5, 6, 7, 8] Ex2: girl_names = ['Joanne', 'Karen', 'Lori'] boy_names = ['Chris', 'Jerry', 'Will'] all_names = girl_names + boy_names print(all_names) OUTPUT: ['Joanne', 'Karen', 'Lori', 'Chris', 'Jerry', 'Will']

You can also use the += augmented assignment operator to concatenate one list to another. list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list1 += list2 The last statement appends list2 to list1. After this code executes, list2 remains unchanged, but list1 references the following list: [1, 2, 3, 4, 5, 6, 7, 8] girl_names = ['Joanne', 'Karen', 'Lori'] girl_names += ['Jenny', 'Kelly'] print(girl_names) OUTPUT: ['Joanne', 'Karen', 'Lori', 'Jenny', 'Kelly'] >>>

What will the following code display? mylist = ['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune'] print(mylist[0::2])

['mercury', 'earth', 'jupiter', 'uranus']

What will the following code display? numbers = list(range(3)) print(numbers)

[0, 1, 2]

Which list will be referenced by the variable number after the following code is executed? number = range(0, 9, 2)

[0, 2, 4, 6, 8]

What will be the value of the variable list after the following code executes? list = [1, 2, 3, 4] list[3] = 10

[1, 2, 3, 10]

What will the following code display? numbers = [1, 2, 3, 4, 5] my_list = numbers[:] print(my_list)

[1, 2, 3, 4, 5]

What will the following code display? numbers1 = [1, 2, 3] numbers2 = [10, 20, 30] numbers2 += numbers1 print(numbers1) print(numbers2)

[1, 2, 3] [10, 20, 30, 1, 2, 3]

What will the following code display? numbers1 = [1, 2, 3] numbers2 = [10, 20, 30] numbers3 = numbers1 + numbers2 print(numbers1) print(numbers2) print(numbers3)

[1, 2, 3] [10, 20, 30] [1, 2, 3, 10, 20, 30]

What will the following code display? numbers = [1, 2, 3, 4, 5] numbers[2] = 99 print(numbers)

[1, 2, 99, 4, 5]

What will the following code display? numbers = [10] * 5 print(numbers)

[10 , 10, 10, 10, 10]

What will the following code display? numbers = [1, 2, 3, 4, 5] my_list = numbers[:1] print(my_list)

[1]

What will the following code display? numbers = [1, 2, 3, 4, 5] my_list = numbers[1:3] print(my_list)

[2, 3]

What will the following code display? numbers = [1, 2, 3, 4, 5] my_list = numbers[-3:] print(my_list)

[3, 4, 5]

What will the following code display? mylist = [1, 2, 3, 4, 5] print (mylist[2:])

[3, 4, 5]

Which of the following would you use if an element is to be removed from a specific index?

a del statement

Given that a refers to a list, write the necessary code to reverse the elements of the list.

a.reverse()

insert Method

allows you to insert an item into a list at a specific position. You pass two arguments to the insert method: an index specifying where the item should be inserted and the item that you want to insert

Sequence Two types: Lists- are mutable (contents can be changed) Tuples- immutable (once it is created, its contents cannot be changed)

an object that holds multiple items of data, stored one after the other. You can perform operations on a sequence to examine and manipulate the items stored in it.

The ________ method is commonly used to add items to a list.

append

Totaling the Values in a List

assuming a list contains numeric values, to calculate the total of those values you use a loop with an accumulator variable; the loop steps through the list, adding the value of each element to the accumulator

The append Method

commonly used to add items to a list. The item that is passed as an argument is appended to the end of the list's existing elements

Passing a List as an Argument to a Function as a program grows larger and more complex, it should be broken down into functions that each performs a specific task. This makes the program easier to understand and to maintain. You can easily pass a list as an argument to a function. This gives you the ability to put many of the operations that you perform on a list in their own functions. When you need to call these functions, you can pass the list as an argument.

def greet_users(names): """Print a simple greeting to everyone.""" for name in names: msg = "Hello, " + name + "!" print(msg) usernames = ['hannah', 'ty', 'margot'] greet_users(usernames)

This program asks the user to enter a grocery item and checks it against a grocery code list. Fill in the missing if statement to display the expected output. Expected Output Enter an item: ice cream The item ice cream was not found in the list.

def main(): # Create a lisof grocery items. ---> grocery_list = ['apples', 'peanut butter', 'eggs', 'spinach', 'coffee', 'avocado'] # Search for a grocery item. ---> search = input('Enter an item: ') # Determine whether the item is in the list. ---> if search in grocery_list: ------> print('The item', search, 'was found in the list.') else: ------> print('The item', search, 'was not found in the list.') # Call the main function. main()

Given that k refers to a non-negative int and that alist has been defined to be a list with at least k+1 elements, write a statement that removes the element at index k.

del alist[k]

What are the data items in a list called?

elements

This program lists a series of even numbers and then selects the number 12 to display. Fill in the last statement with the missing code to display the expected output. Expected Output [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] [12]

evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] print(evens) print(evens[5]) or print(evens[5:6:1]

Complete the program below display the following output. Expected Output [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] [2, 4, 6, 8, 10] [12, 14, 16, 18, 20] [2] [20]

evens = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] print(evens) print(evens[:5]) print(evens[5:]) print(evens[:1], evens[9:])

Look at the following list comprehension: [x for x in my_list] What is the result expression? What is the iteration expression?

for x in list my_list

a variable current_members that refers to a list, and a variable member_id that has been assigned a value. Write some code that assigns True to the variable is_a_member if the value assigned to member_id can be found in the current_members list. Otherwise, assign False to is_a_member. In your code, use only the variables current_members, member_id, and is_a_member.

if member_id in current_members: ---> is_a_member = True else: ---> is_a_member = False

The __________ method searches for an item in the list and returns the index of the first element containing that item.

index

The __________ method inserts an item into the list at a specified index.

insert

The built-in function ________ returns the length of a sequence.

len

The following program creates three lists, list1,list2, and list3. Write a statement that creates a fourth list named list4 that contains the contents of list3 followed by the contents of list2 followed by the contents of list1. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

list1 = [9, 10, 11, 12] list2 = [5, 6, 7, 8] list3 = [1, 2, 3, 4] list4 = list3 + list2 + list1 print(list4)

The del Statement The remove method you saw earlier removes a specific item from a list, if that item is in the list. Some situations might require you remove an element from a specific index, regardless of the item that is stored at that index. This can be accomplished with the del statement. Here is an example of how to use the del statement:

my_list = [1, 2, 3, 4, 5] print('Before deletion:', my_list) del my_list[2] print('After deletion:', my_list) This code will display the following: Before deletion: [1, 2, 3, 4, 5] After deletion: [1, 2, 4, 5]

reverse Method simply reverses the order of the items in the list. Here is an example:

my_list = [1, 2, 3, 4, 5] print('Original order:', my_list) my_list.reverse() print('Reversed:', my_list) This code will display the following: Original order: [1, 2, 3, 4, 5] Reversed: [5, 4, 3, 2, 1]

Negative Indexing You can also use negative indexes with lists to identify element positions relative to the end of the list. The Python interpreter adds negative indexes to the length of the list to determine the element position. The index −1 identifies the last element in a list, −2 identifies the next to last element, and so forth.

my_list = [10, 20, 30, 40] print(my_list[−1], my_list[−2], my_list[−3], my_list[−4]) OUTPUT 40 30 20 10

len Function returns the length of a sequence, such as a list

my_list = [10, 20, 30, 40] size = len(my_list) The first statement assigns the list [10, 20, 30, 40] to the my_list variable. The second statement calls the len function, passing the my_list variable as an argument. The function returns the value 4, which is the number of elements in the list. This value is assigned to the size variable The len function can be used to prevent an IndexError exception when iterating over a list with a loop. Here is an example: my_list = [10, 20, 30, 40] index = 0 while index < len(my_list): ---> print(my_list[index]) ---> index += 1

The min and max Functions Python has two built-in functions named min and max that work with sequences. The min function accepts a sequence, such as a list, as an argument and returns the item that has the lowest value in the sequence. Here is an example:

my_list = [5, 4, 3, 2, 50, 40, 30] print('The lowest value is', min(my_list)) This code will display the following: The lowest value is 2 The max function accepts a sequence, such as a list, as an argument and returns the item that has the highest value in the sequence. Here is an example: my_list = [5, 4, 3, 2, 50, 40, 30] print('The highest value is', max(my_list)) This code will display the following: The highest value is 50

sort Method rearranges the elements of a list so they appear in ascending order (from the lowest value to the highest value)

my_list = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3] print('Original order:', my_list) my_list.sort() print('Sorted order:', my_list) When this code runs, it will display the following: Original order: [9, 1, 0, 2, 8, 6, 7, 4, 5, 3] Sorted order: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] EX 2: my_list = ['beta', 'alpha', 'delta', 'gamma'] print('Original order:', my_list) my_list.sort() print('Sorted order:', my_list) When this code runs, it will display the following: Original order: ['beta', 'alpha', 'delta', 'gamma'] Sorted order: ['alpha', 'beta', 'delta', 'gamma']

Given a list named play_list, write an expression whose value is the length of play_list.

n = len(play_list)

Assume the following statement appears in a program: names = [] Which of the following statements should you use to add the string 'Wendy' to the list at index 0?

names.append('Wendy') because the index is blank you can't set names[0] = 'Wendy' because there is no 0 index. The index is blank.

Given the lists, lst1 and lst2, create a new sorted list consisting of all the elements of lst1 that also appears in lst2. For example, if lst1 is [4, 3, 2, 6, 2] and lst2 is [1, 2, 4], then the new list would be [2, 2, 4]. Note that duplicate elements in lst1 that appear in lst2 are also duplicated in the new list. Assign the new list to the variable new_list, and don't forget to sort the new list.

new_list = [] for elements in lst1: ---> if elements in lst2: -----> new_list.append(elements) new_list.sort()

Repetition Operator when the operand on the left side of the * symbol is a sequence (such as a list) and the operand on the right side is an integer, it becomes the repetition operator. The repetition operator makes multiple copies of a list and joins them all together. list * n In the general format, list is a list, and n is the number of copies to make. NOTE: Most programming languages allow you to create sequence structures known as arrays, which are similar to lists, but are much more limited in their capabilities. You cannot create traditional arrays in Python because lists serve the same purpose and provide many more built-in capabilities.

numbers = [0] * 5 print(numbers) OUTPUT: [0, 0, 0, 0, 0] In line 1, the expression [0] * 5 makes five copies of the list [0] and joins them all together in a single list. The resulting list is assigned to the numbers variable. In line 2, the numbers variable is passed to the print function. The function's output is shown in line 3. numbers = [1, 2, 3] * 3 print(numbers) OUTPUT [1, 2, 3, 1, 2, 3, 1, 2, 3]

Lists are Mutable which means their elements can be changed. Consequently, an expression in the form list[index] can appear on the left side of an assignment operator.

numbers = [1, 2, 3, 4, 5] print(numbers) numbers[0] = 99 print(numbers) line 2 will display: [1, 2, 3, 4, 5] The statement in line 3 assigns 99 to numbers[0]. This changes the first value in the list to 99. When the statement in line 4 executes, it will display: [99, 2, 3, 4, 5] When you use an indexing expression to assign a value to a list element, you must use a valid index for an existing element or an IndexError exception will occur. numbers = [1, 2, 3, 4, 5] # Create a list with 5 elements. numbers[5] = 99 # This raises an exception! The numbers list that is created in the first statement has five elements, with the indexes 0 through 4. The second statement will raise an IndexError exception because the numbers list has no element at index 5. If you want to use indexing expressions to fill a list with values, you have to create the list first: # Create a list with 5 elements. numbers = [0] * 5 # Fill the list with the value 99. index = 0 while index < len(numbers): ----> numbers[index] = 99 ----> index += 1 The statement in line 2 creates a list with five elements, each element assigned the value 0. The loop in lines 6 through 8 then steps through the list elements, assigning 99 to each one.

Iterating over a List with the for Loop

numbers = [99, 100, 101, 102] ----> for n in numbers: print(n) OUTPUT: 99 100 101 102

This program creates a list named numbers that includes numbers from 100 through 1000 at steps of 50. Type two statements into the interface below, the first to create the numbers list, and the second to print the list. Expected Output [100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000]

numbers = list(range(100, 1050, 50)) print(numbers)

List Here is a statement that creates a list of integers: even_numbers = [2, 4, 6, 8, 10] The items that are enclosed in brackets and separated by commas are the list elements. After this statement executes, the variable even_numbers will reference the list names = ['Molly', 'Steven', 'Will', 'Alicia', 'Adriana'] This statement creates a list of five strings. A list can hold items of different types, as shown in the following example: info = ['Alicia', 27, 1550.87] This statement creates a list containing a string, an integer, and a floating-point number. After the statement executes, the info variable will reference the list

object that contains multiple data items. Each item that is stored in a list is called an element. 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. numbers = [5, 10, 15, 20] print(numbers) OUTPUT [5, 10, 15, 20]

Given that play_list has been defined to be a list, write a statement that sorts the list.

play_list.sort()

Assume that play_list refers to a non-empty list, and that all its elements are integers. Write a statement that assigns a new value to the first element of the list. The new value should be equal to twice the value of the last element of the list.

play_list[0] = 2 * play_list[-1]

Given that k and j each refer to a non-negative integer and that play_list has been defined to be a list with at least j + 1 elements, write an expression that evaluates to a new list containing all the elements from the one at index k through the one at index j of list play_list. Do not modify play_list.

play_list[k:j+1]

Write a statement that defines plist as a list containing these elements (in order): 'spam', 'eggs', 'vikings'.

plist = ['spam', 'eggs', 'vikings'] print(plist)

Write a statement that defines plist to be an empty list

plist = []

Write a statement that defines plist as a list containing these elements (in order): 10, 20, 30, ..., 100 in that order

plist = list(range(10, 110, 10)) print(plist)

Given a variable named plist that refers to a list, write a statement that adds another element, 5 to the end of the list.

plist.append(5)

Given that k refers to an integer that is non-negative and that plist1 has been defined to be a list with at least k+1 elements, write a statement that defines plist2 to be a new list that contains all the elements from index k of plist1 and beyond. Do not modify plist1.

plist2= plist1[k::+1]

Given that plist1 and plist2 both refer to lists, write a statement that defines plist3 as a new list that is the concatenation of plist1 and plist2. Do not modify plist1 or plist2

plist3 = plist1 + plist2

Assume that plist has been defined to be a list of 30 integers. Write a statement that adds 5 to its last element.

plist[-1] += 5 DON'T FORGET REVERSE INDEXING

Given a variable plist, that refers to a non-empty list, write an expression that refers to the first element of the list.

plist[0]

Assume that a variable named plist refers to a list with 12 elements, each of which is an integer. Assume that the variable k refers to a value between 0 and 6. Write a statement that assigns 15 to the list element whose index is k.

plist[k] = 15

Finding Items in Lists with the in Operator you can use the in operator to determine whether an item is contained in a list item in list In the general format, item is the item for which you are searching, and list is a list. The expression returns true if item is found in the list, or false otherwise.

prod_nums = ['V475', 'F987', 'Q143', 'R688'] search = input('Enter a product number: ') Basically looks for the specific objects in the list i.e V475 If you say 4 will not find anything You can use the not in operator to determine whether an item is not in a list. Here is an example: if search not in prod_nums: ---> print(search, 'was not found in the list.') else: ---> print(search, 'was found in the list.')

remove Method

removes an item from the list. You pass an item to the method as an argument, and the first element containing that item is removed. This reduces the size of the list by one element. All of the elements after the removed element are shifted one position toward the beginning of the list. A ValueError exception is raised if the item is not found in the list.

Given that play_list has been defined to be a list, write an expression that evaluates to a new list containing the elements at index 0 through index 4 in play_list. Do not modify play_list.

result = play_list[0:5:]

The __________ method reverses the order of the items in the list.

reverse

The __________ method sorts the items in the list to appear in ascending order.

sort

List Methods and Useful Built-in Functions 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. No exceptions will occur if you specify an invalid index. 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 (from the lowest value to the highest value). 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

This program creates a list of five highest mountains and checks another well-known mountain, Kilimanjaro, against the list. Fill in the missing if statement to display the expected output. Expected Output Kilimanjaro is not on the top five list. ['Everest', 'K2', 'Kangchenjunga', 'Lhotse', 'Makalu']

top_five_mountains = ['Everest', 'K2', 'Kangchenjunga', 'Lhotse', 'Makalu'] if 'Kilimanjaro' not in top_five_mountains: ---> print('Kilimanjaro is not on the top five list.') else: ---> print('Kilimanjaro is one of the top five tallest mountains.') ---> print(top_five_mountains)

This program is meant to display weekday abbreviations, but there is an error. Correct the error in the code. Expected Output Mon Tues Wed Thurs Fri

weekdays = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri'] for counter in range(5): ----> print(weekdays[counter]) ----> counter += 1


Set pelajaran terkait

Chapter 37: Nursing Care of the Child With an Infection

View Set

BAS 282: Strategic Planning: Homework

View Set

Chapter 6 Functions Review Questions

View Set