- 40 Algorithms Every Programmer Should Know
- Imran Ahmad
- 449字
- 2025-04-04 12:59:10
Using lists
Utility functions in data structures make them very useful as they can be used to manage data in lists.
Let's look into how we can use them:
- List indexing: As the position of an element is deterministic in a list, the index can be used to get an element at a particular position. The following code demonstrates the concept:
>>> bin_colors=['Red','Green','Blue','Yellow']
>>> bin_colors[1]
'Green'
The four-element list created by this code is shown in the following screenshot:

Note that the index starts from 0 and therefore Green, which is the second element, is retrieved by index 1, that is, bin_color[1].
- List slicing: Retrieving a subset of the elements of a list by specifying a range of indexes is called slicing. The following code can be used to create a slice of the list:
>>> bin_colors=['Red','Green','Blue','Yellow']
>>> bin_colors[0:2]
['Red', 'Green']
Note that lists are one of the most popular single-dimensional data structures in Python.
While slicing a list, the range is indicated as follows: the first number (inclusive) and the second number (exclusive). For example, bin_colors[0:2] will include bin_color[0] and bin_color[1] but not bin_color[2]. While using lists, this should be kept in mind as some users of the Python language complain that this is not very intuitive.
Let's have a look at the following code snippet:
>>> bin_colors=['Red','Green','Blue','Yellow']
>>> bin_colors[2:]
['Blue', 'Yellow']
>>> bin_colors[:2]
['Red', 'Green']
If the starting index is not specified, it means the beginning of the list, and if the ending index is not specified, it means the end of the list. The preceding code actually demonstrates this concept.
- Negative indexing: In Python, we also have negative indices, which count from the end of the list. This is demonstrated in the following code:
>>> bin_colors=['Red','Green','Blue','Yellow']
>>> bin_colors[:-1]
['Red', 'Green', 'Blue']
>>> bin_colors[:-2]
['Red', 'Green']
>>> bin_colors[-2:-1]
['Blue']
Note that negative indices are especially useful when we want to use the last element as a reference point instead of the first one.
- Nesting: An element of a list can be of a simple data type or a complex data type. This allows nesting in lists. For iterative and recursive algorithms, this provides important capabilities.
Let's have a look at the following code, which is an example of a list within a list (nesting):
>>> a = [1,2,[100,200,300],6]
>>> max(a[2])
300
>>> a[2][1]
200
- Iteration: Python allows iterating over each element on a list by using a for loop. This is demonstrated in the following example:
>>> bin_colors=['Red','Green','Blue','Yellow']
>>> for aColor in bin_colors:
print(aColor + " Square")
Red Square Green Square Blue Square Yellow Square
Note that the preceding code iterates through the list and prints each element.