ScanSkill

list in python

The list is used to store multiple items sequentially in one variable. A list is equivalent to an array in other languages. And the list is mutable.

Syntax

  • Empty list initialization
llist_name = [] 
  • Non-empty list initialization
list_name2 = [item1, item2] 
  • Add to a list
list_name.append(item)
  • Access item from the list
list_name[index] 

Note: Items inside of the list can be of different types. Data structures and other lists can also be stored within a list. The array index range is from 0 to size minus 1. Negative indices start at the end of the array and work backward. Lists can be added (using the addition operator) or concatenated (using the extend function).

Examples

>>> cities = ["Kathmandu", "Beni", "Pokhara"]
>>> print (cities[0])
Kathmandu

>>> print(cities[1])
Beni

Add a new item to the list:

>>> cities = ["Kathmandu", "Beni", "Pokhara"]
>>> cities.append("Chitwan")
>>> cities
["Kathmandu", "Beni", "Pokhara", "Chitwan"]