How to Add / Append items to a list in Python

To add items to a list in python is a very general task that you might come across.

Here we have an empty list that we are populating with 10 items using the append method.

n = 10

list = []
for i in range(n):
list.append(input())

print list

That’s it!

Common Mistake

its a common mistake of doing something like this

n=10
list=[]
for i in range(n):
list[i]=input()

this will throw an error IndexError: list assignment index out of range

Because the list is empty and list[i] is trying to access index which does not exist!

Leave a Reply

Your email address will not be published.