Skip to main content

Access Items

Every list item has an index number, and that number is how you reach it:

Note: Indexes begin at 0, so that is where the first item sits.

Example

Index 1 gives us the second item:

Prompt
Create a list of fruits and print the second item using its index.
Output: complete Python program

Negative Indexing

A negative index counts backward from the end of the list.

So -1 is the final item, -2 is the one just before it, and so on.

Example

Get the final item and print it:

Prompt
Create a list of fruits and print the last item using negative indexing.
Output: complete Python program

Range of Indexes

To get several items at once, give a start and an end for the range.

The result comes back as a new list holding just those items.

Note: In the first example, the range begins at index 2, which is included, and stops at index 5, which is left out. Keep in mind that counting begins at 0.

Example

Get the items in third, fourth and fifth position:

Prompt
Create a list of seven fruits and print items from index 2 to 5 (not included) using a range of indexes.
Output: complete Python program

Example

Leave out the start and the range begins at the first item, stopping just before "kiwi":

Prompt
Create a list of seven fruits and print items from the beginning up to (not including) index 4.
Output: complete Python program

Example

Leave out the end and the range runs from "cherry" through the last item:

Prompt
Create a list of seven fruits and print items from index 2 to the end of the list.
Output: complete Python program

Range of Negative Indexes

A range can also use negative indexes, which count back from the end of the list:

Example

The range covers "orange" (-4) up to "mango" (-1), but "mango" itself is left out:

Prompt
Create a list of seven fruits and use negative indexes to print items from index -4 to -1 (not included).
Output: complete Python program

Check if Item Exists

The in keyword tells you whether a given item is in a list:

Example

Test whether the list contains "apple":

Prompt
Create a list of fruits and use the "in" keyword to check if "apple" is present. Print a message if it is.
Output: complete Python program