Lists in Python

A List is basically a sequence which contains a number of values called items. It can hold different types of values.

Lists are ordered, changeable and indexed whose items are surrounded by square brackets [] and must be separated with a comma(,).

This article will tell you about:

How to create a list in Python?

To create a list, a variable is defined which refers to the list.

Syntax:
list_name = [ item1, item2, item3 . . . ]

Example:

month = ["jan", "feb", "mar", "apr", "may"]
print(month)

Output:

['jan', 'feb', 'mar', 'apr', 'may']
  •  A list can also be created using a list constructor.

    Syntax:
    list_name = list(( item1, item2, item3...))

    Example:

    month = list(("jan","feb","mar","apr","may"))
    print(month)

    Output:

    ['jan', 'feb', 'mar', 'apr', 'may']

     

Indexing of the list items

A list is an ordered sequence which means that every item in the list has an index. To refer to an item of the list for accessing, the index of the items is very important.

The index of the first item is always zero.

The index can also be negative which starts from -1. The last item has the index -1.

How to access the items in the list?

You need 2 things to access the items of a list.

  1. Name of the list
  2. Index of the item within square brackets

Syntax:
list_name[index]

Example:

city = ["Agra","Mumbai","Pune","Panjim"]
print ("Item at index 1 :", city[1]) 
print ("Item at index 3 :", city[3])

Output:

Item at index 1 : Mumbai
Item at index 3 : Panjim

Explanation:
Here, city[1] will access the item at index 1 and city[3] will access the item at index 3.

Let us try accessing the items with negative indices.

Example:

city = ["Agra","Mumbai","Pune","Panjim"]
print("Item at index -1: ", city[-1])
print("Item at index -4: ", city[-4])

Output:

Item at index -1: Panjim
Item at index -4: Agra

 

Slicing in Python List

You can also access more than one item of the list in one go. It is called slicing because this feature lets you access a slice(part) of the list.

Syntax:

list_name[a:b]
This statement will access the items from index a to b-1. It is mandatory to separate a and b with a colon.

or
list_name[a:]
This statement will access the items from index a to the last item in the list

or
list_name[:b]
This statement will access the items from the first index to index b-1.

Example:

marks = [20,25,23,27,22,30,28]
print("marks = ", marks)
print("marks[1:5] = ", marks[1:5])
print("marks[1:] = ", marks[1:])
print("marks[:5] = ", marks[:5])

 Output:

marks = [20, 25, 23, 27, 22, 30, 28]
marks[1:5] = [25, 23, 27, 22]
marks[1:] = [25, 23, 27, 22, 30, 28]
marks[:5] = [20, 25, 23, 27, 22]

 

How to change the value of an item in the List?

You can change the value of an item with the help of its index and assignment operator.

Syntax:
List_name[index of the item] = new value

Example:

city = ["Agra","Mumbai","Pune","Panjim"]
print (city)
city[1] = "Nagpur" #changing the value at index 1
print ("After modification:", city)

Output:

['Agra', 'Mumbai', 'Pune', 'Panjim']
After modification: ['Agra', 'Nagpur', 'Pune', 'Panjim']

How to delete a List in Python?

You can delete an existing list with the help of del keyword.

Syntax:
del list_name

Example:

city = ["Agra","Mumbai","Pune","Panjim"]
del city #deleting the list
print(city)

Output:

NameError: name 'city' is not defined

Explanation:
As the list is deleted, the print statement generates an error saying 'city' is not defined.

For loop with List in Python

You can traverse the items of the list using the for loop.

Syntax:
for x in list_name:
     Loop body

Example:

city = ["Agra", "Mumbai", "Pune", "Panjim"]
for x in city:
    print(x)

Output:

Agra
Mumbai
Pune
Panjim

 

Length of the List

The length of the list tells you the number of items present in the list. To find out the length of a list, len() function is used. The list name is given as an argument to the function and it returns an integer value which represents the length of the list.

Syntax:
len(list_name)

Example:

city = ["Agra","Mumbai","Pune","Panjim"]
l = len(city)
print ("Length of the list CITY = ", l)

Output:

Length of the list city = 4

Explanation:
Here, the length of the list city is calculated. The value returned by the len() function is referred by a variable l which is printed in the next statement.

List Methods in Python

There are many operations that can be performed on the lists using built-in functions available in python.

1. insert()

This method is used to insert an item at the given position in a list.

It takes 2 arguments:

  • index of the desired position.
  • value of the new item.

As the new item is added to the list, the index of the items gets modified accordingly.

Syntax:
list_name.insert(index, value)

Example:

city = ["Agra","Mumbai","Pune","Panjim"]
print(city)
city.insert(0, "Nagpur")
print("After insertion of new item: ", city)

Output:

['Agra', 'Mumbai', 'Pune', 'Panjim']
After insertion of new item: ['Nagpur', 'Agra', 'Mumbai', 'Pune', 'Panjim']

2. append()

This method is used to add new items in the list after the last item.

It takes only one argument.

  • The value of the new item.

Syntax:
list_name.append(value)

Example:

city=["Agra","Mumbai","Pune","Panjim"]
print(city)
city.append("Jabalpur")
print("After appending the new item: ", city)

Output:

['Agra', 'Mumbai', 'Pune', 'Panjim']
After appending the new item: ['Agra', 'Mumbai', 'Pune', 'Panjim', 'Jabalpur']

3. remove()

You can remove a particular item from the list using remove method.

It takes one argument.

  • The value of the item to be removed.

The item which matches with the value passed as the argument is removed from the list.

Syntax:
list_name.remove(value)

Example:

city=["Agra","Mumbai","Pune","Panjim"]
print(city)
city.remove("Agra")
print("After removing the item :", city)

Output:

['Agra', 'Mumbai', 'Pune', 'Panjim']
After removing the item : ['Mumbai', 'Pune', 'Panjim']

Note: If the list contains two or more identical items, the remove() method will remove only the first item having the specified value.

Example:

age=[23,30,24,19,20,23,45,23]
print(age)
age.remove(23)
print("After removing the item :", age)

Output:

[23, 30, 24, 19, 20, 23, 45, 23]
After removing the item : [30, 24, 19, 20, 23, 45, 23]

Explanation:
In the above program, the list age contained three identical items with value 23. But only the first item is removed by the function.

 4. pop()

This method deletes and returns the value of the specified item from the list.

It takes one argument:

  • The index of the item to be removed.

If the index is not provided to the function, then by default, pop() deletes the last item of the list.

Syntax:
list_name(index)

Example:

city=["Agra","Mumbai","Pune","Panjim"]
print (city)
a=city.pop(1) #value returned by the function is assigned to a variable.
print("Removed item:", a)
print("After removing the item :", city)

Output:

['Agra', 'Mumbai', 'Pune', 'Panjim']
Removed item: Mumbai
After removing the item : ['Agra', 'Pune', 'Panjim']

5. clear()

This method is used to delete all the items from the list.

No argument is passed to the function.

Syntax:
list_name.clear()

Example:

city=["Agra","Mumbai","Pune","Panjim"]
print(city)
city.clear()
print("After clearing the list: ", city)

Output:

['Agra', 'Mumbai', 'Pune', 'Panjim']
After clearing the list: [ ]

6. extend()

This method is used to add the items of a list to another list.

It takes one argument.

  • The name of the list to be added.

Syntax:
list_name.extend(LIST)

Example:

city=["Agra","Mumbai","Pune","Panjim"]
country=["India","Australia","China","Thailand"]
print(city)
city.extend(country)
print("After extending the list : ",city)

Output:

['Agra', 'Mumbai', 'Pune', 'Panjim']
After extending the list : ['Agra', 'Mumbai', 'Pune', 'Panjim', 'India', 'Australia', 'China', 'Thailand']

7. count()

This method counts the number of times the given item appears in the list.

It takes one argument:

  • The value of the item which is to be counted.

Syntax:
list_name.count(value)

Example:

number = [2,4,6,3,7,2,2,6,4,7,3]
count = number.count(2)
print("Item 2 appears", count, "times in the list.")

Output:

Item 2 appears 3 times in the list.

8. index()

This metohd returns the index of the given item. If there is more than one item with the same value, then the index of the first occurring item is returned.

It takes one argument:

  • The value of the item whose index is required.

Syntax:
list_name.index(value)

Example:

city = ["Agra","Mumbai","Pune","Panjim"]
index = city.index("Pune")
print("Index of the item Pune : ", index)

Output:

Index of the item Pune : 2

Concatenation and Multiplication of Python Lists

Python allows you to concatenate and multiply lists using operators.

Concatenation: This operation connects two or more individual lists and creates a new list. + operator is used to concatenate the lists.

Syntax:
list_name1 + list_name2 + . . .

Example:

a = [1,2,3]
print("List a = ", a)
b = ["x","y","z"]
print("List b = ",b)
c = a + b #concatenation
print("a + b = ", c)

Output:

List a = [1, 2, 3]
List b = ['x', 'y', 'z']
a + b = [1, 2, 3, 'x', 'y', 'z']


Multiplication: This operation simply replicates a list  by a given number of times. * operator is used to multiply a list.

Syntax:
List_name * x
x is the number of times you want to multiply the list.

Example:

a = [1,2,3]
print("List a = ", a)
c = a * 3
print("a * 3 = ", c)

Output:

List a = [1, 2, 3]
a * 3 = [1, 2, 3, 1, 2, 3, 1, 2, 3]