Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - List Methods

Python

python logo

In this tutorial we will learn about list methods in Python.

In the previous tutorial Python - List we learned about lists. Feel free to check that out.

Quick recap

  • A list is an ordered sequence of items.
  • We create lists in Python using the [ ].
  • Items inside the list are indexed.
  • Indexing starts from 0.

Alright, let's get started with list methods.

append

We use the append method to append the passed object to a list.

In the following Python program we are appending objects to a list.

# list
myList = []

print("Starting", myList)

# append integer
myList.append(1)

# append float
myList.append(3.14)

# append string
myList.append("Yusuf Shakeel")

# append complex number
myList.append((2+3j))

# append boolean
myList.append(True)

# append list
myList.append([1,2,3])

# output
print("Final", myList)

The above Python code will give use the following output.

Starting []
Final [1, 3.14, 'Yusuf Shakeel', (2+3j), True, [1, 2, 3]]

clear

We use the clear method to remove all the items from a given list.

In the following Python code we are removing all the items from the list.

# list
myList = [1, 2, 3]

print("before", myList)

# clear
myList.clear()

# output
print("after", myList)

The above code will give the following output.

before [1, 2, 3]
after []

copy

We use the copy method to make a copy of an existing list.

In the following Python program we are creating a copy of a given list.

# list
myList = [1, 2, 3]

# copy
newList = myList.copy()

# output
print(newList)

count

We use the count method to find the total number of times a given object appears in a given list.

In the following Python program we are checking the number of times the given items appear in the list.

# list
myList = [1, 2, 3, 2, 4, "Hello", "Happy", "happy", "hello"]

# count
print(myList.count("unknown"))  # 0
print(myList.count("Hello"))    # 1
print(myList.count("happy"))    # 1
print(myList.count(2))          # 2

extend

We use the extend method to append a sequence of items to an existing list.

It does not returns any value. It simply appends the sequence.

In the following Python program we are appending fruitList to vegList.

# list
vegList = ["Tomato", "Onion", "Potato", "Broccoli", "Lettuce"]

print("before", vegList)

# second list
fruitList = ["Apple", "Mango", "Orange", "Guava", "Watermelon"]

# extend
vegList.extend(fruitList)

# output
print("after", vegList)

We get the following output for the above code.

before ['Tomato', 'Onion', 'Potato', 'Broccoli', 'Lettuce']
after ['Tomato', 'Onion', 'Potato', 'Broccoli', 'Lettuce', 'Apple', 'Mango', 'Orange', 'Guava', 'Watermelon']

index

We use the index method to get the first occurrence of a given value in a list.

On success, this method returns the index of the item. If the item is not found then it gives an exception.

In the following Python program we are finding 6 in the given list.

# list
myList = [1, 2, 5, 6, 4, 3, 6, 7, 9, 8]

# index
print(myList.index(6))     # 3

The above code will give us 3 as the first occurrence of digit 6 is at index 3.

Note! Even though we have 6 appearing twice in the list but the index method will return the index were it first encountered 6.

insert

We use the insert method to insert an object at a specific index in the list.

Here are the possible ways we can insert item in a list.

Insert at the start

Following is the syntax to insert an item at the start (0th index) of the list.

list.insert(0, item)

Where, list is a variable that holds the list and item is the item that is getting inserted in the list at the start (0th index).

Note! Item present at the specific index is not delete but shifted to make room for the new item.

In the following Python program we are inserting string "Happy" at index 0 (start of the list).

# list
myList = [1, 2, 3, 4, 5]

print("before", myList)

# insert
myList.insert(0, "Hello")

# output
print("after", myList)

The above code will give use the following output.

before [1, 2, 3, 4, 5]
after ['Hello', 1, 2, 3, 4, 5]

Note! In the above output we can see that item 1 is moved from index 0 and it's position is taken by the inserted item "Hello".

Insert at the end

Following is the syntax to insert an item at the end of the list.

list.insert(len(list), item)

We use the len method to get the total number of items in the list.

In the following Python program we are inserting string "Happy" at the end of the list.

# list
myList = [1, 2, 3, 4, 5]

print("before", myList)

# insert
myList.insert(len(myList), "Hello")

# output
print("after", myList)

The above code will give use the following output.

before [1, 2, 3, 4, 5]
after [1, 2, 3, 4, 5, 'Hello']

If we set the insert index to a value greater than the total item present in the list then the new item will be inserted at the end.

In the following Python program the new item is inserted at the end of the list.

# list
myList = [1, 2, 3, 4, 5]

print("before", myList)

# insert
myList.insert(100, "Hello")

# output
print("after", myList)

We will get the following output.

before [1, 2, 3, 4, 5]
after [1, 2, 3, 4, 5, 'Hello']

Insert between start and end

If we give any index that falls between the start and the end index of the list then the new item will be inserted somewhere within the list.

In the following Python program we have a list of 5 numbers and we are inserting the string "Hello" somewhere in between.

# list
myList = [1, 2, 3, 4, 5]

print("before", myList)

# insert
myList.insert(3, "Hello")

# output
print("after", myList)

The above Python program will give us the following output.

before [1, 2, 3, 4, 5]
after [1, 2, 3, 'Hello', 4, 5]

pop

We use the pop method to pop items from the list.

This method returns the popped item.

If we don't pass any index then pop method will pop the last item from the list.

In the following Python program we are popping out the last item from the given list.

# list
myList = [1, 2, 3, 4, 5]

print("before pop:", myList)

# pop
x = myList.pop()

# output
print("Pop", x)
print("after pop:", myList)

We get the following output.

before pop: [1, 2, 3, 4, 5]
Pop 5
after pop: [1, 2, 3, 4]

We can also pop items from a specific index using the following syntax.

list.pop(index)

In the following Python program we are popping out item at index 3.

# list
myList = [1, 2, 3, 4, 5]

print("before pop:", myList)

# pop
x = myList.pop(3)

# output
print("Pop", x)
print("after pop:", myList)

The above Python program will give us the following output.

before pop: [1, 2, 3, 4, 5]
Pop 4
after pop: [1, 2, 3, 5]

remove

We use the remove method to remove an item from the list.

Syntax

list.remove(item)

In the following Python program we are removing 3 from the list.

# list
myList = [1, 2, 3, 4, 5]

print("before", myList)

# remove
myList.remove(3)

# output
print("after", myList)

Output:

before [1, 2, 3, 4, 5]
after [1, 2, 4, 5]

reverse

We use the reverse method to reverse the order of the items in the list.

In the following Python program we are reversing the order of the items in the list.

# list
myList = [1, 2, 3, 4, 5]

print("before", myList)

# reverse
myList.reverse()

# output
print("after", myList)

We will get the following output.

before [1, 2, 3, 4, 5]
after [5, 4, 3, 2, 1]

sort

We use the sort method to sort the items of a list in ascending and descending order.

By default the items are sorted in ascending order.

In the following Python program we are sorting the items of the list in ascending order.

# list
myList = [1, 10, 9, 6, 3, 8, 2, 5, 4, 7]

print("before", myList)

# sort
myList.sort()

# output
print("after", myList)

We will get the following output.

before [1, 10, 9, 6, 3, 8, 2, 5, 4, 7]
after [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

To sort the item in descending order we use the following syntax.

list.sort(reverse=True)

In the following Python program we are sorting the items of the list in descending order.

# list
myList = [1, 10, 9, 6, 3, 8, 2, 5, 4, 7]

print("before", myList)

# sort
myList.sort(reverse=True)

# output
print("after", myList)

The above Python program will give use the following output.

before [1, 10, 9, 6, 3, 8, 2, 5, 4, 7]
after [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT