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!

Comments

Popular posts from this blog

How to install python-gst (pygst) in ubuntu 16.04

How to make a gui Calculator in Python using Tkinter

How to Install Antlr4 in Ubuntu/Linux