Course 5.1Lesson 1 of 5
A list holds many values in one variable. It is written in square brackets with commas between the values. Positions start at 0, and negative positions count from the end. A slice takes a piece and stops before the last position. len() gives the number of items, and in asks whether a value is in the list. A list can hold numbers, text, True and False, a mix of them, or nothing at all. Asking for a position that does not exist gives an IndexError.
Try the code and the simulations beside the lesson.
After this lesson you can
IndexError.A class has 30 students, and each has a mark. To keep the marks, you would need mark1, mark2, all the way to mark30. That is a lot of names, and a loop could not go through them. It is much better to keep all the marks in one variable. That is what a list is: many values, one name, in a fixed order.
You write a list in square brackets, with commas between the values.
A list shows itself with the square brackets and the commas, exactly as you wrote it. The text items are shown with quotation marks.
Imagine that the list is a row of boxes, and each box has a position number. The positions start at 0, not at 1. This is the same rule as for the letters of a string (Chapter 5). The last box of a list of 4 has the position 3.
What happens if you ask for a position that does not exist?
The numbers under the bars are the positions. A list of 6 items has the positions 0 to 5, and -6 to -1 from the end.
You know the position and want the item: use fruits[2]. You know the item and want its position: use the method index().
Almost everything that you learned about strings works for lists: positions, negative positions, slices, len() and in. There is one big difference: a string cannot be changed, and a list can. The next lesson is about that.
len(a_list). The last position is len(a_list) - 1, or simply -1.fruits[1:2] is ['mango'], with the brackets, and fruits[1] is 'mango'.( ) instead of square brackets. That is a different thing, a tuple.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
index() does when the item occurs twice.a[start:stop] stops before stop and is always a list.len() counts the items. in asks whether a value is in the list. index() gives a position.IndexError.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
["a", "b", "c"][1]?len([4, 7, 9, 12])?[10, 20, 30][-1]?[5, 6, 7, 8][1:3]?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.