USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Lists

Lesson 5/15 | Study Time: 30 Min

Lists in Python


A list in Python is an ordered, mutable collection of items where each item is stored at a particular index starting from zero. A list can store elements of different data types such as integers, strings, floats, or even other lists, making it a highly flexible data structure. Lists allow modification because they are mutable, meaning their content can be changed after creation by adding, removing, or updating elements. Lists are widely used when you need a dynamic container whose size can grow or shrink during the program's execution.


Creating Lists in Python


Creating a list means defining a sequence of elements enclosed in square brackets. A list can be created empty or with initial values. Python allows mixed data types inside a list, and the list stores elements in the same order in which they are written. Because lists are dynamic, new elements can be added later using various methods.

Syntax

list_name = [element1, element2, element3]


Example 

numbers = [10, 20, 30, 40]          # List of integers

mixed_list = [10, "hello", 3.14]    # List with different data types

empty_list = []                     # Creating an empty list



List methods in Python


List methods in Python are built-in functions used to perform different operations on list objects. They help in adding, removing, searching, and modifying elements inside a list easily. Common list methods include append(), insert(), remove(), pop(), sort(), and reverse(). These methods make list manipulation faster and more efficient. Understanding list methods is important for effective data handling in Python programs.




1. Append() Method


The append() method is used to add a single new element at the end of the existing list. This method modifies the original list directly because lists are mutable. When you append an item, the list size increases by one. This method only accepts one element at a time and always places it at the last index of the list.

Syntax

list_name.append(element)


Example

fruits = ["apple", "banana"]

fruits.append("mango")           # Adding "mango" to the end

print(fruits)                    # Output: ['apple', 'banana', 'mango']


2. Insert() Method


The insert() method allows you to add an element at a specific index. When inserting, the existing elements shift to the right to make space for the new value. This method is useful when you want to maintain a particular order in the list and add items at custom positions.

Syntax

list_name.insert(index, element)


Example

colors = ["red", "blue"]

colors.insert(1, "green")        # Insert "green" at index 1

print(colors)                    # Output: ['red', 'green', 'blue']


3. Remove() Method 


The remove() method removes the first occurrence of the given element from the list. It searches the list from left to right and deletes the first match found. If the element does not exist in the list, Python raises a ValueError. This method only removes by value, not by index.

Syntax

list_name.remove(element)


Example

items = ["pen", "pencil", "eraser"]

items.remove("pencil")           # Removes the element "pencil"

print(items)                     # Output: ['pen', 'eraser']


4. Pop() Method


The pop() method removes an element from a specific index and returns that removed value. If no index is provided, it removes the last element by default. This method is useful when you need both removal and retrieval of the element. It reduces the list size by one.

Syntax

list_name.pop(index)


Example

nums = [10, 20, 30, 40]

removed = nums.pop(2)            # Removes element at index 2 → 30

print(removed)                   # Output: 30

print(nums)                      # Output: [10, 20, 40]


5. Sort() Method


The sort() method arranges the elements of the list in ascending order by default. It modifies the original list in place. Sorting works only for lists containing elements that can be compared to each other (e.g., all integers or all strings). You can also sort in reverse order by using a parameter.

Syntax

list_name.sort()


Example

marks = [50, 10, 30, 20]

marks.sort()                     # Sorts in ascending order

print(marks)                     # Output: [10, 20, 30, 50]


6. Reverse() Method


The reverse() method reverses the order of elements in the list. It does not sort the list; it simply flips the list from end to start. Like other mutating methods, it directly modifies the original list, creating a reversed version in place.

Syntax

list_name.reverse()


Example

letters = ["a", "b", "c"]

letters.reverse()                # Reverse order of elements

print(letters)                   # Output: ['c', 'b', 'a']


7. Extend() Method


The extend() method adds multiple elements to the end of a list by taking another iterable such as another list, tuple, or set. Unlike append(), which adds the entire iterable as a single element, extend() breaks the iterable and inserts each element individually.

Syntax

list_name.extend(iterable)


Example

a = [1, 2]

b = [3, 4]

a.extend(b)                      # Adds elements 3 and 4 to list a

print(a)                         # Output: [1, 2, 3, 4]


8. Count() Method



The count() method returns the number of times a particular element appears in the list. It scans the entire list and counts every occurrence of the specified value. This is useful for analyzing frequencies of elements.

Syntax

list_name.count(value)


Example

nums = [1, 2, 2, 3, 2]

print(nums.count(2))             # Output: 3 (2 appears 3 times)


9. Index() Method


The index() method returns the index of the first occurrence of the specified element. If the element is not found, Python raises a ValueError. It searches from the beginning of the list to the end.

Syntax

list_name.index(value)


Example

cities = ["Delhi", "Mumbai", "Chennai"]

print(cities.index("Mumbai"))    # Output: 1 (position of "Mumbai")


10. Clear() Method


The clear() method removes all elements from the list, making it empty. This method is helpful when you want to reuse the same list variable without deleting it.

Syntax

list_name.clear()


Example

data = [10, 20, 30]

data.clear()                     # Removes all elements

print(data)                      # Output: []


11. Copy() Method



The copy() method creates a shallow copy of the list. A shallow copy means it duplicates the list structure but not the nested elements if they are objects. This method is useful when you want a new list that does not affect the original list when modified.

Syntax

list_name.copy()


Example

original = [1, 2, 3]

duplicate = original.copy()      # Creates a new list with same values

print(duplicate)                 # Output: [1, 2, 3]


Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.