Previous Next

Python Lists

A list is a comma-separated ordered collection of data elements enclosed in square brackets. They hold more than one item within one variable.

Example:

list1 = [20, 40, 60]
print(list1)

Output

[20, 40, 60]

Access List Items

Example:

flowers = ["Rose", "Tulip", "Lotus"]
print(flowers[1])

Output

Tulip

Add List Items

There are three ways to add items to a list: append(), insert(), extend().

append()

To add an item at the start of the list, use the append() method.

Example:

flowers = ["Rose", "Tulip", "Lotus"]

flowers.append("Lily")

print(flowers)

Output:

['Rose', 'Tulip', 'Lotus', 'Lily']

insert()

To insert a list item at a specified position, use the insert() method.

Example:

flowers = ["Rose", "Tulip", "Lotus"]

flowers.insert(2, "Lily")

print(flowers)

Output:

['Rose', 'Tulip', 'Lily', 'Lotus']

extend()

The extend() function adds the complete list to the current list. It does not insert but extends to the end of the current list.

Example:

flowers = ["Rose", "Tulip", "Lotus"]
flowers2 = ["Lily", "Tulip", "Iris"]

flowers.extend(flowers2)

print(flowers)

Output:

['Rose', 'Tulip', 'Lotus', 'Lily', 'Tulip', 'Iris']

Remove List Items

There are a variety of methods to delete items from the list.

pop()

The pop() function deletes the last item of the list if no index is used. If an index is used, the item at that given index is deleted.

Example:

flowers = ["Rose", "Tulip", "Lotus"]
flowers.pop()
print(flowers)

Output:

['Rose', 'Tulip']

remove()

The remove() function deletes the given item from the list.

Example:

flowers = ["Rose", "Tulip", "Lotus"]
flowers.remove("Tulip")
print(flowers)

Output:

['Rose', 'Lotus']

clear()

The clear() function deletes all the items from the list and prints an empty list.

Example:

flowers = ["Rose", "Tulip", "Lotus"]
flowers.clear()
print(flowers)

Output:

[]

List Methods

Python has a number of in-built functions for handling lists.

sort()

The sort() function sorts the list in ascending order.

Example:

flowers = ["Rose", "Tulip", "Lotus"]
flowers.sort()
print(flowers)

Output:

['Lotus', 'Rose', 'Tulip']

index()

The index() function will return the index of the list item's first occurrence.

Example:

flowers = ["Rose", "Tulip", "Lotus"]
print(flowers.index("Tulip"))

Output:

1

copy()

The copy() method gives a copy of the list

Example:

flowers = ["Rose", "Tulip", "Lotus"]
newlist = flowers.copy()
print(newlist)

Output:

['Rose', 'Tulip', 'Lotus']
Previous Next