Python's creators wanted its users to actively and effectively use built-in collections.
Therefore, the language inclines the programmer toward a particular work style when choosing an approach. The language itself encourages the use of an imperative style combined with procedural and object-oriented programming.
In Python, collections are objects. We modify them mostly in place, which gives them their modifiable state. However, the language also has a place for elements of functional programming. Developers often consider it a subspecies of declarative programming because functional code looks like a data conversion pipeline.
In this lesson, we'll look at imperative and functional code in Python. In both cases, we'll try displaying a sorted list of unique elements from a set of numbers.
Procedural solution
When we use procedural solutions, we still split the program into subroutines that change the state instead of returning a value. The code will look like this:
INPUT = [1, 2, 5, 12, 3, 5, 2, 7, 12]
def main():
numbers = INPUT[:]
filter_and_sort(numbers) # Sorting and filtering in place
for number in numbers:
print(number) # Outputting element by element in a loop
def filter_and_sort(values):
values.sort() # The list is sorted in place
previous_value = None
index = 0
while index < len(values):
value = values[index]
if value == previous_value and index > 0:
# We remove the item from the list, modifying the list again
values.pop(index)
else:
index += 1