Press ESC to close

Append Python

0 1527

The append method in Python, discussed in the last lesson, is used to insert items at the end of a list.

The syntax of this method is as follows:

list.append (element)

The method accepts only one parameter, the element to be inserted in what to the list.

First exercise with append in Python

There is no better way to learn something than through practice. So let’s do some exercises.

Populate a list of n keyboard integers. At the end of the insertion with another cycle, select one element out of three and add them. Finally, display the sum as output.

So first of all we ask you to enter the number of elements, that is n.

Next, we declare the empty list named integers and initialize the sum to zero.

With a for loop we insert the elements in the list and then with another for loop a step of 3 we select an element every 3.

So we display the sum in output.

So here’s a possible solution using Python’s append method:

n = int(input('How many numbers do you want to enter?: '))
numbers_int = []
s = 0

for i in range(n):
    number = int(input('Insert a number: '))

for i in range(0,n,3):
    s += numbers_int[i]


Second exercise with append in Python

Let’s do a second exercise again using append method.

Enter 20 random numbers from 10 to 100 with a for loop. Then check with another cycle how many values ​​greater than 50 have been entered.

We set the number of elements ie n to 20. Then we initialize the random list to the empty list and add it to 0.

Then with a for loop that goes from 0 to n-1, we fill the list with random values ​​from 10 to 100. For this purpose we use the randint function, of the random module, which generates random numbers among the values ​​set inside the round brackets.

Then with a for loop we calculate how many values ​​greater than 50 have been generated and finally we display the result in output.

So here’s the complete code using append method in Python:

import random

n = 20
numbers_random = []
count = 0

for i in range(n):
    number = random.randint(10,100)

for i in range (n):
    if(numbers_random[i] > 50):
        count += 1


In these exercises we used the append method in Python to insert items at the end of a list, in the next lessons we will deepen this method again.

Some Useful links

Python tutorial

Python Compiler

Install Python


Assignment operators



How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot

Other stories

Euclidean algorithm Python

Next Story

Prime numbers Python

Previous Story