CS 124: Chapter 7 - Lists and Tuples

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Difference between lists and arrays

Arrays are used in other languages such as PHP. Python lists have much more built-in functionality, such as negative indices. However, both lists and arrays use indices to access their data, thus arrays are not needed.

Explain why a programmer would use a tuple instead of a list.

Because they are immutable, tuples can be used as a collection of constants. For example, a tuple containing the names of the months. Processing a tuple is faster than processing a list, so tuples are good choices when you are processing lots of data, and that data will not be modified. Another reason is that tuples are safe. Because you are not allowed to change the contents of a tuple, you can store data in one and rest assured that it will not be modified (accidentally or otherwise) by any code in your program.

list()

Built-in function that can convert a tuple to a list. Example: number_tuple = (1, 2, 3) number_list = list(number_tuple)

tuple()

Built-in function that converts a list to a tuple. Example: str_list = ['one', 'two', 'three'] str_tuple = tuple(str_list)

max() function

Built-in function that returns the highest value in a list. Written in the format max(list).

min() function

Built-in function that returns the lowest value in a list. Written in the format min(list).

slicing expression

an expression that selects a range of elements from a sequence, in the form list[x:y:z], where x = starting index, y = ending index, and z = step value; slicing expressions follow the same behavior as range() more or less.

element

each item stored in a list

Explain how negative indices work in Python

Negative indices work the opposite of regular positive ones. So, [-1] references the last item, [-2] is the next to the last, etc. In other words, negative work like a countdown.

append(item)

Adds item to the end of the list.

IndexError exception

An error/exception that is raised if you use an invalid index with a list.

A list must contain elements of the same data type. (T/F)

False. Lists can contain elements of different types. Example: info = ['Alicia', 27, 1550.87]

in operator

In Python, used to find an item in a list, written as: item in list

Explain how to display the contents of a list.

List contents can be displayed using the print() function by using the name of the list as the parameter. Example: print(info)

remove(item)

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

Explain the key difference between lists and tuples

a list is mutable, which means that a program can change its contents, but a tuple is immutable, which means that once it is created, its contents cannot be changed.

del list[i]

Delete an element from a list at a specific index.

Explain how to create a tuple with only one element

If you want to create a tuple with just one element, you must write a trailing comma after the element's value, as shown here: my_tuple = (1,) # creates a tuple with one element Otherwise, you will create a variable named my_tuple that is assigned whatever value is in the parentheses. my_tuple = (1) # creates an integer variable

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.

Explain how slicing behaves with invalid indices. What exceptions are raised?

Invalid indexes do not cause slicing expressions to raise an exception. For example: - 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.

Python list indices

List indices in Python can be positive or negative numbers. 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.

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.

reverse()

Reverses the order of the items in the list.

sort()

Sorts the items in the list so they appear in ascending order (from the lowest value to the highest value).

Explain indices in two-dimensional lists

The following list: scores = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Is a list that consists of three (3) lists. Because there are three elements in each list, that means scores consists of three (3) rows and three (3) columns. Generally, each individual sub-list represents a row. The number of elements within the sub-list determines the number of columns. It should be noted that the number of columns for each sub-list should match. The elements of that array would be referenced as follows: 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] The elements in row 2 are referenced as follows: scores[2][0] scores[2][1] scores[2][2]

Explain how to copy a list

There are two (2) main methods for copying lists: 1) Linking two separate list variables to the same list. Example: list1 = [1, 2, 3, 4] list2 = list1 Thus, list1 and list2 actually point to the same list contents. So, a change made to list1 will be reflected to list2 - and vice versa. 2) Copy one list to another so that two separate, unlinked, identical lists. There are two (2) methods to accomplish this. Given list1 and list2: 2A) Use for loop to loop through list1 and read each element into list2. Example: list1 = [1, 2, 3, 4] list2 = [] for item in list1: list2.append(item) 2B) Use concatenation (+). Example: list1 = [1, 2, 3, 4] list2 = [] + list1 This also works: list2 = list1 + [5, 6, 7, 8]

What are the key similarities and differences between tuples and lists?

Tuples support all the same operations as lists, except those that change the contents of the list. Tuples support the following: - Subscript indexing (for retrieving element values only) - Methods such as index - Built-in functions such as len, min, and max - Slicing expressions - The in operator - The + and * operators

repetition operator

When the * operator's left operand is a list and its right operand is an integer, a repetition operator makes multiple copies of a list and joins them together. The general format is: list * n Example: numbers = [0] * 5 Output: [0, 0, 0, 0, 0]

two-dimensional list

a list that contains other lists as its elements; also called nested lists. two-dimensional lists are represented as rows and columns, similar to an Excel spreadsheet

tuple

an immutable sequence, which means that its contents cannot be changed (unlike lists). Instead of brackets, tuple definitions use parentheses. Example: my_tuple = (1, 2, 3, 4, 5) However, tuple indices use brackets just like lists. Example: mytuple[0]

list

an object that contains multiple data items; a list is mutable, meaning that a program can change its contents: Examples: even_numbers = [2, 4, 6, 8, 10] names = ['Molly', 'Steven', 'Will', 'Alicia', 'Adriana'] Items within a list also have indices, so they can be accessed as list[n], where list is the name of the list, and n is a whole number which must be enclosed in brackets.

sequence

an object that holds multiple items of data, stored one after the other

list concatenation

joining lists with the + operator or the augmented assignment operator += Example 1: list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list3 = list1 + list2 list3 is now: [1, 2, 3, 4, 5, 6, 7, 8] Example 2: list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] list1 += list2 list1 is now: [1, 2, 3, 4, 5, 6, 7, 8] (list1 has been concatenated with list2 and the results are stored in list1) Example 3: girl_names = ['Joanne', 'Karen', 'Lori'] girl_names += ['Jenny', 'Kelly'] girl_names is now: ['Joanne', 'Karen', 'Lori', 'Jenny', 'Kelly'] Remember that both + and += operators behave as normal. NOTE: lists must be concatenated with other lists. Any attempt to perform these operations with a list and a non-list will result in an exception. Also note that these operations do not change order of elements.

List the two (2) fundamental sequence types in Python

lists and tuples

len function

returns the length of a sequence such as a list Example: my_list = [10, 20, 30, 40] size = len(my_list) In the above example, size is equal to 4

slice

subsection of a sequence; a span of items taken from a sequence. Example 1: days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] mid_days = days[2:5] Explanation: The above statement reads, "take a slice of elements from the list called days beginning with the second index up to but not including five" mid_days now references the following list: ['Tuesday', 'Wednesday', 'Thursday'] Note: in slicing, the starting index refers to the item at index 2, not the second element. which would be 'Monday'. Remember, array indices start at 0 (zero). Example 2: mid_days = days[:5] Result: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'] Explanation: If the starting index is not explicitly defined, zero (0) is assumed. Example 3: mid_days = days[2:] Result: ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] Explanation: If a starting index is defined without a terminating index, the resultant slice will begin at the defined index and continue to the end of the list. Example 4: mid_days = days[-3:] Result: ['Thursday', 'Friday', 'Saturday'] Explanation: In the case of negative indices, start with the index and continue to the end of the list.


Ensembles d'études connexes

Nature and the Environment - English 9A

View Set

Chapter 56: Management of Patients with Dermatologic Disorders and Wounds

View Set

Cardiovascular System: Blood Blood Composition and Erythrocyte Function Dynamic Study Module

View Set

BioA: Cells- Stability and Change

View Set

ATI PN Fundamentals Online Practice 2020 B with NGN

View Set