Changing the items of a List

Changing the items of a List

Lesson Details:
June 29, 2020


I: Introduction

Python is a programming language that was developed in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI) in the Netherlands as a successor of a language called ABC. It was named after Monty Python, a British comedy group known for its surreal humour. Python is a high-level programming language that is considered as an easy to learn and general purpose which can be used for many types of applications including web development, GUI development, and scientific computing.

I: Body

In this part, we will discuss about changing the items of a list using different methods.

In the first example, we create a list of numbers from 1 to 10 and then we change those numbers from 1 to 8 using some different methods.

clear() # Clears all the variables and functions of a program print("Before") print(list1) l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in l: if i > 5: i = i - 5 elif i < 1: i = i + 5 print("After") print(list1)

Output:



In the above example, we have used two different methods of changing the items of a list. In the first method, we have shown how to change the items from 1 to 8 using an “if” statement and the second method we have shown how to change the items from 1 to 5 using an “elif” statement.

The first method is simple and efficient but it has one limitation; we can use it only to change the items up to a specific number. For example, we can use it to change the items from 1 to 5 but not from 1 to 7 or from 1 to 10. If we want to change the items from 1 to 10, we need to use the second method which is not as efficient as the first method but it is flexible. We can use it to change any number of items without limitations.

In our next example, we will show you how both methods work together and increase the efficiency and flexibility of our program. First we create a list with numbers from 1 to 20 and then we change those numbers from 1 to 15 using an “if” statement and we change those numbers from 16 to 20 using an “elif” statement.

clear() # Clears all the variables and functions of a program print("Before") print(list1) l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in l: if i <= 5: i = i - 5 else: i = i - 10 print("After") print(list1)

Output:



The same code works fine for any number of items. We can use it to change the items from 1 to 1000 or more without any changes.

loader
Course content