🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Lists and Tuples.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

GallantReal

Uploaded by GallantReal

2021

Tags

python data science programming

Full Transcript

‫ر‬ ‫الجامعة السعودية االلكتونية‬ ‫ر‬ ‫االلكت‬ ‫ونية‬ ‫الجامعة السعودية‬ ‫‪26/12/2021‬‬ College of Computing and Informatics Bachelor of Science in Computer Science DS242 - Advanced Data Science Programming DS242 Advanced Data Science Programming Week 3 Speeding Along with Lists and Tuples (Part 1)...

‫ر‬ ‫الجامعة السعودية االلكتونية‬ ‫ر‬ ‫االلكت‬ ‫ونية‬ ‫الجامعة السعودية‬ ‫‪26/12/2021‬‬ College of Computing and Informatics Bachelor of Science in Computer Science DS242 - Advanced Data Science Programming DS242 Advanced Data Science Programming Week 3 Speeding Along with Lists and Tuples (Part 1) Contents 1. Defining and Using Lists Weekly Learning Outcomes 1. Define lists 2. Work with Lists Required Reading (Book 2: Understanding Python Building Blocks) Chapter 3: Speeding Along with Lists and Tuples (John C. Shovic and Alan Simpson, Python All-in-One For Dummies, 2nd edition, 2021). Speeding Along with Lists and Tuples Introduction Sometimes in code you work with one data item at a time, such as a person’s name, unit price, or username. Other times, you work with larger sets of data, such as a list of people’s names or a list of products and their prices. These sets of data are often referred to as lists or arrays in most programming languages. Python has lots of easy, fast, and efficient ways to deal with all kinds of data collections. Defining and Using Lists The simplest data collection in Python is a list. A list is any list of data items, separated by commas, inside square brackets. Typically, you assign a name to the list using an = character, just as you would with variables. If the list contains numbers, don’t use quotation marks around them. For example, here is a list of test scores: scores = [88, 92, 78, 90, 98, 84] Defining and Using Lists If the list contains strings, as always, those strings should be enclosed in single or double quotation marks, as in this example: students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] To display the contents of a list on the screen, you can print it just as you would print any regular variable. For example, executing print(students) in your code after defining that list displays the following on the screen: ['Mark', 'Amber', 'Todd', 'Anita', 'Sandy'] Referencing list items by position Each item in a list has a position number, starting with 0, even though you don’t see any numbers. You can refer to any item in the list by its number using the name for the list followed by a number in square brackets. In other words, use this syntax: listname[x] Referencing list items by position Replace listname with the name of the list you’re accessing and replace x with the position number of the item you want. Remember, the first item is always 0, not 1. For example, in the following first line, we define a list named students, and then print item number 0 from that list. The result, when executing the code, is the name Mark displayed: students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] print(students) Mark Looping through a list To access each item in a list, just use a for loop with this syntax: for x in list: Replace x with a variable name of your choosing. Replace list with the name of the list. An easy way to make the code readable is to always use a plural for the list name (such as students, scores). Then you can use the singular name (student, score) for the variable name. Looping through a list Remember to always indent the code that’s to be executed in the loop. Below code shows a more complete example where you can see the result of running the code in a Jupyter notebook. Seeing whether a list contains an item If you want your code to check the contents of a list to see whether it already contains some item, use in listname in an if statement or a variable assignment. Below code creates a list of names. Then, two variables store the results of searching the list for the names Anita and Bob. Printing the contents of each variable displays True for the one where the name Anita is in the list. The test to see whether Bob is in the list proves False. Getting the length of a list To determine how many items are in a list, use the len() function (short for length). Put the name of the list inside the parentheses. For example, type the following code in a Jupyter notebook or at the Python prompt or whatever: students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] print(len(students)) Running that code produces this output: 5 Adding an item to the end of a list To add an item to the end of a list, use the.append() method with the value you want to add inside the parentheses. You can use either a variable name or a literal value inside the quotation marks. For instance, in below code, the line students.append("Goober") adds the name Goober to the list. The line students.append(new_student) adds whatever name is stored in the new_student variable to the list. The.append() method always adds to the end of the list. So when you print the list, those two new names are at the end. Adding an item to the end of a list You can use a test to see whether an item is in a list and then append it only when the item isn’t already there. For example, the following code won’t add the name Amanda to the list because that name is already in the list: student_name = "Amanda" #Add student_name but only if not already in the list. if student_name in students: print(student_name + " already in the list") else: students.append(student_name) print(student_name + " added to the list") Inserting an item into a list Whereas the append() method adds an item to the end of a list, the insert() method adds an item to the list in any position. The syntax for insert() is listname.insert(position, item) Replace listname with the name of the list, position with the position at which you want to insert the item. Replace item with the value, or the name of a variable that contains the value, that you want to put in the list. Inserting an item into a list For example, the following code makes Lupe the first item in the list: # Create a list of strings (names). students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] student_name = "Lupe" # Add student name to front of the list. students.insert(0, student_name) # Show me the new list. print(students) Output for the code: ['Lupe', 'Mark', 'Amber', 'Todd', 'Anita', 'Sandy'] Changing an item in a list You can change an item in a list using the = assignment operator just like you do with variables. Make sure you include the index number in square brackets to indicate which item you want to change. The syntax is: listname[index] = newvalue Replace listname with the name of the list; replace index with the subscript (index number) of the item you want to change; and replace newvalue with whatever you want to put in the list item. Changing an item in a list For example, look at the following code: # Create a list of strings (names). students = ["Mark", "Amber", "Todd", "Anita", "Sandy"] students = "Hobart" print(students) Output for the code: ['Mark', 'Amber', 'Todd', 'Hobart', 'Sandy'] Combining lists If you have two lists that you want to combine into a single list, use the extend() function with the following syntax: original_list.extend(additional_items_list) In your code, replace original_list with the name of the list to which you’ll be adding new list items. Replace additional_items_list with the name of the list that contains the items you want to add to the first list. Combining lists For example, look at the following code using lists named list1 and list2. After executing list1.extend(list2), the first list contains the items from both lists, as you can see in the output of the print() statement at the end. # Create two lists of Names. list1 = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] list2 = ["Huey", "Dewey", "Louie", "Nader", "Bubba"] # Add list2 names to list1. list1.extend(list2) # Print list 1. print(list1) ['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake', 'Huey', 'Dewey', 'Louie', 'Nader’, 'Bubba'] Removing list items Python offers a remove() method so you can remove any value from the list. If the item is in the list multiple times, only the first occurrence is removed. The following code displays a list of letters with the letter C repeated a few times. # Create a list of strings. letters = ["A", "B", "C", "D", "C", "E", "C"] # Remove "C" from the list. letters.remove("C") Then the code uses letters.remove("C") # Show me the new list. print(letters) to remove the letter C from the list: ['A', 'B', 'D', 'C', 'E', 'C'] Removing list items If you need to remove all of an item, you can use a while loop to repeat the.remove as long as the item still remains in the list. For example, this code repeats the.remove as long as “C” is still in the list: while "C" in letters: letters.remove("C") If you want to remove an item based on its position in the list, use pop() with an index number rather than remove() with a value. If you want to remove the last item from the list, use pop() without an index number. Removing list items The following code creates a list, removes the first item (0), and then removes the last item (pop() with nothing in the parentheses). Printing the list proves that those two items have been removed: # Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] # Remove the first item. letters.pop(0) # Remove the last item. letters.pop() # Show me the new list. print(letters) Running the code shows that popping the first and last items did, indeed, work: ['B', 'C', 'D', 'E', 'F'] Removing list items When you pop() an item off the list, you can store a copy of that value in some variable. Below code shows the same code as the preceding, but it stores copies of what’s been removed in variables named first_removed and last_removed. At the end it prints the list, and also shows which letters were removed. Removing list items Python also offers a del (short for delete) command that deletes any item from a list based on its index number (position). But again, you have to remember that the first item is 0. So, let’s # Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] say you run the following code to # Remove item sub 2. del letters delete item number 2 from the print(letters) list: ['A', 'B', 'D', 'E', 'F', 'G'] Clearing out a list To delete the contents of a list but not the list itself, use.clear(). The list still exists, but it contains no items. In other words, it’s an empty list. The following code shows how you could test this. Running the code displays [] at the end, which lets you know the list is empty: # Create a list of strings. letters = ["A", "B", "C", "D", "E", "F", "G"] # Clear the list of all entries. letters.clear() # Show me the new list. print(letters) [] Counting how many times an item appears in a list use the Python count() method to count how many times an item appears in a list. As with other list methods, the syntax is simple: listname.count(x) Replace listname with the name of your list, and x with the value you’re looking for (or the name of a variable that contains that value). Counting how many times an item appears in a list The below code counts how many times the letter B appears in the list, using a literal B inside the parentheses of.count() like this: grades.count("B") Because B is in quotation marks, you know it’s a literal, not the name of some variable. Finding a list item’s index Python offers an.index() method that returns a number indicating the position of an item in a list, based on the index number. The syntax is: listname.index(x) In the below example where the program crashes at the line f_index = grades.index(look_for) because there is no F in the list. Finding a list item’s index An easy way to get around this problem is to use an if statement to see whether an item is in the list before you try to get its index number. If the item isn’t in the list, display a message saying so. Otherwise, get the index number and show it in a # Create a list of strings. grades = ["C", "B", "A", "D", "C", "B", "C"] # Decide what to look for look_for = "F" # See if the item is in the list. message. That code follows: if look_for in grades: # If it's in the list, get and show the index. print(str(look_for) + " is at index " + str(grades.index(look_for))) else: # If not in the list, don't even try for index number. print(str(look_for) + " isn't in the list.") Alphabetizing and sorting lists Python offers a sort() method for sorting lists. In its simplest form, it alphabetizes the items in the list (if they’re strings). If the list contains numbers, they’re sorted smallest to largest. For a simple sort like that, just use sort() with empty parentheses: Created a new list for each simply by assigning each sorted list to a new list name. listname.sort() Reversing a list You can also reverse the order of items in a list using the.reverse() method. This is not the same as sorting in reverse. When you sort in reverse, you still sort: Z–A for strings, largest to smallest for numbers, and latest to earliest for dates. When you reverse a list, you simply reverse the items in the list, no matter their order, without trying to sort them. Reversing a list In the following code, we reverse the order of the names in the list and then print the list. # Create a list of strings. names = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] # Reverse the list. names.reverse() # Print the list. print(names) ['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara'] Copying a list If you need to work with a copy of a list so as not to alter the original list, use the.copy() method. The following code is similar to the # Create a list of strings. names = ["Zara", "Lupe", "Hong", "Alberto", "Jake"] preceding code, except that instead of # Make a copy of the list. backward_names = names.copy() reversing the order of the original list, we make a copy of the list and reverse that one. Printing the contents of each list shows how the first list is still in the original order whereas the second one is reversed: # Reverse the copy. backward_names.reverse() # Print the list. print(names) print(backward_names) ['Zara', 'Lupe', 'Hong', 'Alberto', 'Jake'] ['Jake', 'Alberto', 'Hong', 'Lupe', 'Zara'] Methods for Working with Lists Thank You DS242 Advanced Data Science Programming Week 4 Speeding Along with Lists and Tuples (Part 2) Contents 1. What’s a Tuple and Who Cares? 2. Working with Sets Weekly Learning Outcomes 1. Understanding the tuples using python 2. Understanding the difference between a set and a list is that the items in a set have no specific order Required Reading (Book 2: Understanding Python Building Blocks) Chapter 3: Speeding Along with Lists and Tuples (John C. Shovic and Alan Simpson, Python All-in-One For Dummies, 2nd edition, 2021). What’s a Tuple and Who Cares? Introduction In addition to lists, Python supports a data structure known as a tuple. But it’s not spelled tupple or touple, so our best guess is that it’s pronounced “two-pull.” A tuple is a list, but you can’t change it after it’s defined. The syntax for creating a tuple is the same as the syntax for creating a list, except you don’t use square brackets. You have to use parentheses, like this: prices = (29.95, 9.98, 4.95, 79.98, 2.95) What’s a Tuple Most of the techniques and methods that you learned for using lists back in slide 39, don’t work with tuples because they are used to modify something in a list, and a tuple can’t be modified. you can get the length of a tuple using len, like this: print(len(prices)) You can use.count() to see how many times an item appears in a tuple. For example: print(prices.count(4.95)) What’s a Tuple You can use in to see whether a value exists in a tuple, as in the following sample code: print(4.95 in prices) This returns True if the tuple contains 4.95 or False if it doesn’t. If an item exists in the tuple, you can get its index number. You’ll get an error, though, if the item doesn’t exist in the list. look_for = 12345 if look_for in prices: position = prices.index(look_for) else: position = -1 print(position) What’s a Tuple You can loop through the items in a tuple and display them in any format you want by using format strings. For example, this code displays each item with a leading dollar sign and two digits for the pennies: # Loop through and display each item in the tuple. for price in prices: print(f"${price:.2f}") The output from running this code with the sample tuple follows: $29.95 $9.98 $4.95 $79.98 $2.95 What’s a Tuple You can’t change the value of an item in a tuple using this kind of syntax: prices = 234.56 You’ll get an error message that reads TypeError: 'tuple' object does not support item assignment. (This message is telling you that you can’t use the assignment operator, =, to change the value of an item in a tuple because a tuple is immutable, meaning its content cannot be changed.) A tuple makes sense if you want to show data to users without giving them any means to change any of the information. Working with Sets Introduction Python also offers sets as a means of organizing data. The difference between a set and a list is that the items in a set have no specific order. Even though you may define the set with the items in a certain order, none of the items get index numbers to identify their position. To define a set, use curly braces where you use square brackets for a list and parentheses for a tuple. For example, here’s a set with some numbers in it: sample_set = {1.98, 98.9, 74.95, 2.5, 1, 16.3} Working with Sets Sets are similar to lists and tuples in a few ways. You can use len() to determine how many items are in a set. Use in to determine whether an item is in a set. But you can’t get an item in a set based on its index number. Nor can you change an item already in the set. You can’t change the order of items in a set either. You can’t use.sort() to sort the set or.reverse() to reverse its order. Working with Sets You can add a single new item to a set using.add(), as in the following example: sample_set.add(11.23) Not that unlike a list, a set never contains more than one instance of a value. (So even if you add 11.23 to the set multiple times, the set will still contain only one copy of 11.23.) You can also add multiple items to a set using.update(). (But the items you’re adding should be defined as a list in square brackets), as in the following example: sample_set.update([88, 123.45, 2.98]) Working with Sets You can copy a set. However, because the set has no defined order, when you display the copy, its items may not be in the same order as the original set, as shown in this code and its output: # Define a set named sample_set. sample_set = {1.98, 98.9, 74.95, 2.5, 1, 16.3} # Show the whole set print(sample_set) # Make a copy and show the copy. ss2 = sample_set.copy() print(ss2) {1.98, 98.9, 2.5, 1, 74.95, 16.3} {16.3, 1.98, 98.9, 2.5, 1, 74.95} Working with Sets The below code creates a set named sample_set and then uses a variety of print() statements to output information. Each number is neatly formatted with two digits, because the code uses the f-string >6.2f, which right aligns each number with two digits after the decimal point. Summary Lists and tuples are two of the most commonly used Python data structures. Sets don’t seem to get as much play as the other two, but it’s good to know about them. Thank You

Use Quizgecko on...
Browser
Browser