A common task in software engineering is list manipulation. In this example we convert a list of salaries to a new list of salaries, where each salary is raised by 20%.
We use 4 different methods for this:
We start with the traditional approach and loop throught the list of salaries, take an element from the list, multiply by 1.2 and append the result to a target list.
salaries = [2000, 2200, 1800, 1900, 2400] raised_salaries = [] for s in salaries: raised_salaries.append(s * 1.2) for s in raised_salaries: print(s)
Output:
2400.0 2640.0 2160.0 2280.0 2880.0
salaries = [2000, 2200, 1800, 1900, 2400] def raise_salary(salary): return salary * 1.2 raised_salaries = map(raise_salary, salaries) for s in raised_salaries: print(s)
Output:
2400.0 2640.0 2160.0 2280.0 2880.0