So far, we’ve needed a new variable name for each new piece of information we wanted to store. A list is a Python data type that can store multiple pieces of information, in order, and with a single variable name. The list name, together with a non-negative integer can then be used to refer to the individual items of data. Let’s start with an example: Show
Notice that we can use There are two main uses of lists:
Creating listsYou can type a list in using brackets and commas. When the Python interpreter reaches the brackets, Python allocates space in memory for the items in the list. Of course, usually there’s not much point in just printing out a list created this way; we’d like
to be able to refer to the list with a variable name. The assignment operator
Strictly speaking, it’s incorrect to say “ You can also create an empty list.
For now, we don’t have much use for empty lists, but we’ll soon see that we can start with an empty list and then add items to it. Exercise: star powerObjective: Create a list with data and make use of that list by passing it to a function. The vertices of a star centered the middle of a small drawing area are (161, 86), (119, 80), (100, 43) (81, 80), (39, 86), (70, 116), (63, 158), (100, 138), (137, 158), (130, 116). In the code below, the Here is a solution. Accessing items of a listOnce a list has been created and its address assigned to a variable, you will want to do things with individual items of the list. We use square brackets to index into a list. The first list element is at index 0 (because that’s how computer scientists like to count: starting from 0), so to get the 0th item in the list, follow the name of the list variable with square brackets containing the number 0. What goes within the brackets can be any expression that evaluates to an int that is in the range of the indices: Notice that list items can really be treated as variables. You can use the assignment operator to change an item in a list (
Common programming error: List index out of rangeIf you forget that the list is indexed from 0, or for some other reason try to access an item of the list at an index beyond the end of the list, Python will abort your program and print an error message. The following code fails, because there are only items at indices 0, 1, and 2: This is a very common type of programming error. If you get an error like
from Python, step through your code by hand near the line where Python reports an error, and figure out how you managed to ask for a list index that isn’t in the list. There are two cases:
The length of a listYou can find out how many items are in a list using the Python built-in function Iterating over a list with a while-loopA list is a way of organizing, or structuring, data that your program will use. We say that a list is a data structure, and we will see many other examples of data structures later in the course. One of the key principles of a data structure is that the data structure allows you to apply operations to some or all of the data in a unified way. Let’s take an example. You decide to start a new website,
But then next month, the United States decides to convert to the Celsius scale, leaving the Bahamas, Belize, the Cayman Islands, and Jamaica as the only countries using the Fahrenheit scale. You decide to convert all of your temperatures to Celsius. You could do it this way: (Notice the floating-point inaccuracies. I told you so.) You are doing the same type of operation over and over again. Convert This while-loop would work for even a very long list of temperatures. Exercise: falling starObjective: Modify the data in a list using a while loop. The code below draws a star in the center of the screen. Re-write the code so that the star slowly falls from its starting position downwards. Here is a solution. An algorithm design and implementation example: reversing a listLet’s look at an example in which we want to reverse a list. Recall from the first chapter that a fully specified step-by-step strategy for solving a problem in computer science is called an algorithm. The first step to solving a problem is to think about how we might solve it as a human, as precisely as possible. Once each step has been fully specified, we have designed an algorithm. We then translate that algorithm into runnable code, thereby implementing the algorithm. There are two choices for our reverse_list algorithm:
We’ll use the second approach and reverse the list in place, since I haven’t yet told you how to make a new list of the correct size. Now let’s think about how to reverse the list in place. What’s our target? We want the first item to be in the last item’s spot, and vice versa. We want the second item to be in the current second-to-last item’s spot, and vice versa. So here is a first attempt at our algorithm specification, in English (or pseudo-code):
Will it work? Let’s walk through it in our heads for a list of length 6. Start by swapping the first item with the sixth. Good. Swap the second item with the fifth. Good. Swap the third item with the fourth. Good. The next item is the fourth item. Houston, we have a problem. After we swapped the third item with the fourth, we actually were done—the list was reversed. If we then swap the fourth with the third, as our first attempt at an algorithm seems to specify, we put them back to where they were when we started. We have begun to undo our reversal of the list items. We need to modify our algorithm so that it stops after swapping only half of the items in the list.
There’s one more thing we should be nervous about. A list of length 6 has a first half and a second half, each of size 3. What if we had a list of length 7? What’s the first half? What’s the second? How many swaps should we do? Well, the item that is precisely in the middle of an odd-length list doesn’t get changed by reversing the list. So for a list of length 7, we need to do only 3 swaps. If the list length is odd, the number of swaps is the length of the list, divided by 2, and rounded down. If the list length is even, the number of swaps is the length of the list divided by 2. So our final algorithm design is:
Now let’s implement the reverse_list algorithm in Python code. We need to loop through the first half (rounded down) of the list. We can use a while-loop for that. There are a few tricky things to notice. First, we can accomplish the
rounding down of the index of the middle item of the list by just using integer division ( Also, because indices in a list start at 0, we have to be careful about computing the index into the second half of the list. It’s good to check an example. Suppose the list The final thing to notice is how we swap items. We need a temporary variable to hold one of the values. Suppose you tried something like this:
The both items of the list would end up having the
same value after the first line, and the original value of If needing a temporary variable confuses you, think of it this way. Suppose that Nicole and Tom want to exchange the positions of their two cars in their two-car garage. Tom’s Chevy starts on the left side, and Nicole’s Honda starts on the right. Tom can’t just drive his Chevy out onto the right side. No, he has to put his Chevy in the driveway (the temporary storage), then put Nicole’s Honda in the left side, and finally move his Chevy to the right side. Appending to an existing listIf you have an existing list and would like to add an item to the end, you can do that with the The syntax for What’s
the period doing in Exercise: circle artObjective: Append items to a list in response to user input. Modify the following program so that it lets the user draw circles on the screen while dragging the mouse with the button pressed. Do not delete or in any other way prevent the Here is a solution. Inserting into and deleting from listsThere are a couple more list operations that you should know about. You can insert an item into a list and delete an item from the list using the To delete an item, you just write To insert into a list, you call the We often use a loop to work with items of a list when programming. This section introduces a new type of loop, called a for-loop, that is particularly well suited to dealing with items of a list. Anything you can accomplish with a for-loop you can also accomplish with a while-loop, so we are not getting any more power out of for-loops. But we’ll see that they are easier to read and to type. Alternate, briefer ways of expressing the same thing in code are called syntactic sugar, because they’re just a sweet extra. Before we get to for-loops, let’s look at another example with a while-loop. A particularly common case is when you would like to use each item in a list, but do not want to actually change the list. Here is an example of simply printing out all of the items of a list: You might notice that in the above loop, the variable If you were describing the method for printing out the names of moons at a high level, you might say (in English)
something like, “For every item of the A for-loop iterates over items in a list, making each item available in sequence. Here is an example, in moons_for.py, that acts identically to the example with the while-loop. With a for-loop, you don’t need to create an index variable, increment the index variable, or compare the index variable to the length of the list. Python does that stuff for you internally, behind the scenes. There are a couple of key things to notice.
Because for-loops are simpler and easier to read, you should use a for-loop in your code wherever the goal is to refer to the items of a list, but without changing the list. If you want to change which items the list contains, you should use a while-loop. Using range to create a list of int valuesSome functions return lists. For example, the built-in Python function
Notice that the last number in the list is 9, not 10.
If you only give the By calling and Exercise: bubblesObjective: Access and modify lists in a for loop using an index variable. The following program adds x and y coordinates to lists to represent bubbles in water. Write a for-loop that draws all of the bubbles, and moves every bubble upwards one pixel after it is drawn. Notice that since the bubbles are originally placed below the bottom of the screen, you will not see anything at first; your program might need to run for a while. For debugging, you could increase the frequency of bubbles and place them higher up on the screen. Here is a solution. You can treat a string like a list (sort of)You can get a character from a string almost as though the string were a list: You can even loop over characters in a string, You might think you could change a character in a string this way too. It won’t work. If you wanted to do something like changing the third letter to r, you would have to build an entirely new string, using the old string and the new letter. We’ll see how to do that later in the course. How it works: The list in memoryConsider when we first assign to a variable, such as Something different happens when you create a list. Space in memory is allocated for the list somewhere other than at the variable’s address. The variable just stores the address of the list. Let’s look at an example:
Here is what happens. First, Python sees a list literal on the right-hand side of the equals sign. Python finds memory space for the list data Now Python looks
at the left-hand side of the assignment operator. Python has to create a new variable, I drew the arrow to indicate that the variable Important note. It would be incorrect to say that the variable We cannot store a list in a variable, because the list could have any size at all. But just like integer values, all addresses have the same size, so we know how much space in a variable to use for an address. Aliasing and the assignment operatorBecause the address of a list is stored in a variable, rather than actually storing the list data itself in the variable, an important property follows: any variable that stores that address can be used to change the list. Look at this example: This program prints
Notice that What happened here? The assignment operator always copies the value of a variable. But in this case, the value of the variable Now, when the item at index 3 in the list whose address is held in I wrote the item at index 3 in italics just to highlight it. When we print the list using the You can think of it like this. Let’s say you have a savings account number. You can think of that number as the address used to refer to a pile of money in some bank vault somewhere. Now if the bank assigns me the same address (savings account number), then I can use that number to withdraw half of the money. When you go to look at the account, half of the money is gone. When two names refer to the same thing, those names are called aliases of each other. Dr. Dre and Andre Ramelle Young both refer to the same person. Aliasing can be a source of tricky-to-find bugs. (You might view it as a bug if I withdrew half of your money from your savings account, and you didn’t even know that we had the same account number.) For integers, floats, or booleans, the assignment operator makes a new copy of the data, not a copy of the address, so for these primitive types, changing the value of one variable never has an effect on the value of another variable. For strings, the assignment operator copies the address, but because strings are immutable, you’ll never notice that aliasing is occurring. Why the difference between how primitive types and lists are treated? Lists can be long, and copying a long list can take a long time, relatively speaking. Copying the address of the list might be enough. We’ll see later that we can still tell Python that we really do want to copy the list itself, and not just the address, using a special function Passing lists to functions (and aliasing)If you pass the address of a list to a function, then the function can change the data at that address. The function does not change the value of the parameter which is passed to it, which is just some address of a list. But the data contained within the list itself is changed. Exercise: function for reversing a listObjective: Take an implementation of a list algorithm, and wrap it in a function that takes the list as a parameter. Reversing a list seems like a useful thing to do; we already wrote the code to do it. Aliasing lets us move that code into a function. Write a function Here is a solution. Copying a list with listSometimes, you really do want a copy of a list. You can use the function Sorting a list with sortedPython contains a useful built-in function, Run it, and look at the output. How does the Good programming practice: Lists should contain only data of similar typesIt is possible to store different types of items in a single list. However, you should avoid doing so most of the time.
The problem is that if you want to apply some operation to all items of the list, you can’t be sure that it makes sense to do so. Imagine you tried to sort How do you change a list element in a for loop in Python?Use a for-loop and list indexing to modify the elements of a list. a_list = ["a", "b", "c"]. for i in range(len(a_list)): Iterate over numbers `0` up to `2`. a_list[i] = a_list[i] + a_list[i] Modify value in place.. Can you modify a list while in a for loop?The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.
How do you modify a list element in Python?Example 1: Change Single list item.. Change first element mylist[0]=value.. Change third element mylist[2]=value.. Change fourth element mylist[3]=value.. Can you modify individual list elements Python?Lists in Python are mutable. All that means is that after defining a list, it is possible to update the individual items in a list.
|