Quiz - Lists/Tuples

¡Supera tus tareas y exámenes ahora con Quizwiz!

Tuples

>>> testScore = ('Mark', 85) >>> testScoreList = [('Mark', 85), ('Quinn', 92), ('Kyle', 79)] >>> for t in range(len(testScoreList)): print(testScoreList[t]) Tuples do not support the methods: append remove insert reverse sort 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

Accessing Values in Tuples

>>> tup1 = ('physics', 'chemistry', 1997, 2000); >>> tup2 = (1, 2, 3, 4, 5, 6, 7 ); >>> print "tup1[0]: ", tup1[0] >>> print "tup2[1:5]: ", tup2[1:5] tup1[0]: physics tup2[1:5]: [2, 3, 4, 5]

List operations

The + operator concatenates lists: >>> x = ['a', 'b', 'c'] >>> y = ['d', 'e', 'f'] >>> z = x + y >>> print (z) ['a', 'b', 'c', 'd', 'e', 'f'] Similarly, the * operator repeats a list a given number of times: >>> [0] * 5 [0, 0, 0, 0, 0]

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

Traversing a List

The most common way to traverse the elements of a list is with a for loop: for pie in pies: print (pie)

There are several ways to create a new list.

The simplest is to enclose the elements in square brackets (AKA a "list display") pies = ['Apple', 'Pumpkin', 'Pecan', 'Cherry'] Python also supports computed lists, called "list comprehensions. The syntax is: newList = [expression for variable in sequence] squares = [x**2 for x in range(10)]

Deleting List Elements

There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop: >>> pies = ['Apple', 'Pumpkin', 'Pecan', 'Cherry'] >>> pieSlice = pies.pop(1) note the parenthesis ...not [ ] >>> print (pies) ['Apple', 'Pecan', 'Cherry'] >>> print (pieSlice) Pumpkin If you don't need the removed value, you can use the del operator: >>> del pies[1]

Copying Lists

To make a copy of a list you must copy each element of the list Several 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 copy - returns a copy of the list. >>> pies = ['Apple', 'Pumpkin', 'Pecan', 'Cherry'] >>> piesBackup = pies.copy() equivalent to a[:] >>> print piesBackup ['Apple', 'Pumpkin', 'Pecan', 'Cherry']

Two-Dimensional Lists

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

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.

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

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

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

Sequence:

an object that contains multiple items of data The items are stored in sequence one after another

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 Methods

append - adds a new element to the end of a list: >>> x = ['a', 'b', 'c'] >>> x.append('d') note there are no [ ] >>> print (x) ['a', 'b', 'c', 'd'] extend - takes a list as an argument and appends all of the elements: >>> x1 = ['a', 'b', 'c'] >>> y1 = ['d', 'e', 'f'] >>> x1.extend(y1) >>> print (x1) ['a', 'b', 'c', 'd', 'e', 'f'] sort - arranges the elements of the list from low to high: >>> v = ['d', 'c', 'e', 'b', 'a'] >>> v.sort() >>> print v ['a', 'b', 'c', 'd', 'e']

print function

can be used to display an entire list

list() function

can convert certain types of objects to lists list("April Showers") list(range(10))

Write a list to a file

def main(): cities = ['Houston', 'Austin', 'Galveston', 'Dallas'] outfile = open('c:\\TestData\\cities.txt', 'w') for item in cities: outfile.write(item + '\n') outfile.close() main()

Read a file into a list

def main(): infile = open('c:\\TestData\\cities.txt', 'r') cities = infile.readlines() infile.close() index = 0 while index < len(cities): cities[index] = cities[index].rstrip('\n') index += 1 main()

List Methods and Useful Built-in Functions

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 >>> v = ['d', 'c', 'e', 'b', 'a'] >>> v.index('e') >>> v.index('z') reverse(): reverses the order of the elements in the list >>> v.reverse() >>> print v ['e', 'd', 'c', 'b', 'a'] insert(index, item): used to insert item at position index in the list >>> v.insert(3, 'z') >>> print v what will print? 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

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

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

Mutable sequence

the items in the sequence can be changed Lists are mutable, and so their elements can be changed An expression such as >>> pies[0] = "Blueberry" >>> print (pies[0]) Blueberry


Conjuntos de estudio relacionados

Chapter 16: Injuries to the Lower Leg, Ankle And Foot

View Set

new and improved world history study guide lol

View Set

The flow of food: Service Chp. 7

View Set

public and other goods; international trade

View Set

3.3 Some Proteins Act as Enzymes to Speed up Biochemical Reactions

View Set