Skip to main content

Retrieving Single Elements

This lesson shows how to get one element out of a list: by its position, by a condition, or at random. It also shows how to check whether an element exists at all.

Python has None, a special value that means "no value". When a lookup can fail, a Python function can return the element or None, and the caller tests the result with is not None.

Reading a position that does not exist, such as words[5] in a list of 5 elements, stops the program with an IndexError (a runtime error). So we either check len() first or use a helper that does.

Other languages have many ready-made functions for this. Python keeps it to a few tools: square brackets, the built-in next() function with a default, and a small helper function you write once.


Retrieve by Position

Every element in a list has a position called an index. The first index is 0, so the last one is len(words)-1.

To read an element by position, write the index inside square brackets: words[3]. Python also counts from the end: a negative index such as words[-1] reads the last element without any length arithmetic.

Python has no element_at_or_none() or element_at_or_else(). A small helper checks the index against len() and returns either the element or None, or the result of a fallback function. This way an out-of-range index cannot raise an IndexError.

Element at a position

words[3] reads the element at index 3. Since counting starts at 0, that is the fourth word.

Prompt
Make a list with the words one, two, three, four, five. Print the element at index 3 using square brackets.
Output: complete Python program
Element at a position

First and last element

The first element is words[0]. The last one is words[-1]: a negative index counts from the end, so -1 is the last element and -2 the one before it.

Prompt
Make a list with the words one, two, three, four, five. Print the first element with index 0, then the last element with index -1.
Output: complete Python program
First and last element

Element at a position, or None

element_at checks the index against len(). Index 1 is in range, so it returns the word two. Index 5 is out of range, so it returns None instead of raising an IndexError.

Prompt
Write an element_at helper that returns the element at an index, or None when the index is out of range. Call it on the words one, two, three, four, five with index 1 and with index 5, and print both results.
Output: complete Python program
Element at a position, or None

Element at a position, or a fallback

element_at_or_else takes a fallback function. The function receives the index, so it can build a message like "The value for index 5 is undefined".

Prompt
Write an element_at_or_else helper that returns the element at an index, or the result of a fallback function that receives the index. Call it on the words one, two, three, four, five with index 5 and a fallback that builds the text "The value for index 5 is undefined". Print the result.
Output: complete Python program
Element at a position, or a fallback

Retrieve by Condition

Often you do not know the position. You know a condition instead: the first word longer than 3 letters, the last word that starts with "f". The condition sits in a generator expression such as w for w in words if len(w) > 3, which produces only the matching words.

For the first match, pass the generator to the built-in next() function. It takes the first value the generator produces and does not look at the rest. When nothing matches, next() raises a StopIteration error — unless you give it a second argument, a default, which is returned instead.

There is no last-match function. reversed() walks the list backwards, so next() over a reversed generator finds the last match: the first hit while walking backwards is the last one in the list.

With None as the default, "nothing matched" is just a result that is None.

First match

next() takes the first word the generator produces with len(w) > 3. That word is three.

Prompt
Make a list with the words one, two, three, four, five. Use next() with a generator expression to find the first word longer than 3 letters and print that word.
Output: complete Python program
First match

Last match

The generator walks reversed(words), so it starts at the end. The first word it meets that starts with "f" is five, so next() returns it and the other words are not checked.

Prompt
Make a list with the words one, two, three, four, five. Use next() over reversed() to find the last word that starts with "f" and print it.
Output: complete Python program
Last match

First match, or None

No word is longer than 6 letters, so next() returns the default None and the program prints "not found". In the numbers list the first even number is 2.

Prompt
Use next() with None as the default. On the words one, two, three, four, five search for a word longer than 6 letters and print "not found" when the result is None. Then search the numbers 1, 2, 3, 4 for the first even number and print it.
Output: complete Python program
First match, or None

Last match, or None

reversed(numbers) walks the numbers backwards. The last even number is 4, and it is found right away.

Prompt
Use next() over reversed() with None as the default on the numbers 1, 2, 3, 4 to find the last even number, and print it when the result is not None.
Output: complete Python program
Last match, or None

Retrieve with Selector

Sometimes you want to change each element first and then take the first result that fits.

A selector function does the change and returns None for results that do not fit. map() applies the selector to every element, and next() with an is not None test takes the first good result. The list here holds a number, a string and a bool at the same time — a Python list can mix types. str() turns any value into text.

First converted value that fits

Each value is turned into text with str(). 0 becomes "0", which is too short, so the selector returns None. "true" has 4 characters, so it is the first result that is not None and the program prints true.

Prompt
Make a list holding 0, the string "true" and False. Write a selector that turns a value into text with str() and returns None when the text has fewer than 4 characters. Print the first selector result that is not None.
Output: complete Python program
First converted value that fits

Random Element

To pick a random element, pick a random index. The random module gives random numbers; rng.randrange(n) returns a number from 0 up to n-1, which is exactly the range of valid indexes.

Python also has rng.choice(), which picks an element directly. This example picks an index first so you can see it; choice() does the same job in one call.

A generator made with random.Random(42) starts from a fixed seed. With the same seed the program picks the same element every time, which makes the output predictable — the example seeds its own generator exactly for that reason. Use random.Random() without a seed when you want a different result on each run.

Pick a random element

With seed 42 the generator picks index 0, so the program prints 1. Change the seed and a different number can come out.

Prompt
Make a list with the numbers 1, 2, 3, 4. Create a random generator seeded with 42 using random.Random, pick a random index with randrange and print the element at that index.
Output: complete Python program
Pick a random element

Check Element Existence

To check whether a value is in a list, use the in operator. It returns True or False.

Python has no contains_all(). The built-in all() does it in one line: all(v in items for v in wanted) is True only when every wanted value is found. It stops as soon as one value is missing.

Python also has no is_empty(). Compare the length: len(s) == 0 means empty, len(s) > 0 means not empty. The Python way is even shorter: an empty list counts as False in a condition, so most Python code writes if not words: for "empty" and if words: for "not empty". This page prints the length checks because they say exactly what is measured.

Contains one value

"four" is in the list, so the first check is True. "zero" is not, so the second check is False.

Prompt
Make a list with the words one, two, three, four, five. Use the in operator to check whether "four" is in the list and whether "zero" is in the list. Print both answers.
Output: complete Python program
Contains one value

Contains all values

Both "four" and "one" are in the list, so contains_all returns True. "zero" is missing, so the second call returns False.

Prompt
Write a contains_all helper that returns True only when every value of a second list is found in the first list, using all() and the in operator. Check the words one, two, three, four, five for four and one, then for one and zero. Print both answers.
Output: complete Python program
Contains all values

Empty or not empty

empty has length 0, so len(empty) == 0 is True. words has 5 elements, so len(words) > 0 is also True.

Prompt
Make a list with the words one, two, three, four, five and an empty list. Print whether the length of the empty list is 0, then whether the length of the words list is greater than 0.
Output: complete Python program
Empty or not empty