Skip to main content

Lists in Python

Hey there! In this guide, we'll explore lists in Python. Lists are ordered, mutable collections of elements that allow you to store and manipulate data efficiently. Let's dive in!


Python Lists​

  • Ordered: Elements have a defined order and can be accessed via indices.

  • Mutable: Lists can be modified after creation (add, remove, or change elements).

  • Heterogeneous: Lists can store elements of different data types (e.g., integers, strings, booleans).

  • Supports nesting: Lists can contain other lists as elements (nested lists).

  • Dynamic sizing: Lists can grow or shrink as you add or remove elements.

  • Common methods: Includes methods like append(), extend(), insert(), pop(), remove(), sort(), and reverse().


1. Creating a List​

You can create a list using square brackets [] or the list() function.

my_list = [1, 2, 3, 4, 5]          # Create a list using square brackets
another_list = list(('apple', 'banana', 'cherry')) # Create a list using the list() function
print(my_list) # Output: [1, 2, 3, 4, 5]
print(another_list) # Output: ['apple', 'banana', 'cherry']

2. Accessing Elements​

You can access elements in a list using their index. Python uses zero-based indexing.

my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Access the first element, Output: 10
print(my_list[3]) # Access the fourth element, Output: 40

3. Adding Elements​

You can add new elements to a list using methods like append(), insert(), or extend().

my_list = [1, 2, 3]
my_list.append(4) # Add an element to the end of the list
print(my_list) # Output: [1, 2, 3, 4]

my_list.insert(1, 5) # Insert an element at index 1
print(my_list) # Output: [1, 5, 2, 3, 4]

another_list = [6, 7]
my_list.extend(another_list) # Extend the list by adding elements from another list
print(my_list) # Output: [1, 5, 2, 3, 4, 6, 7]

4. Removing Elements​

You can remove elements from a list using remove(), pop(), or del.

my_list = [1, 2, 3, 4, 5]
my_list.remove(3) # Remove the first occurrence of a value
print(my_list) # Output: [1, 2, 4, 5]

popped_element = my_list.pop(1) # Remove and return the element at index 1
print(popped_element) # Output: 2
print(my_list) # Output: [1, 4, 5]

del my_list[0] # Delete the element at index 0
print(my_list) # Output: [4, 5]

5. List Methods​

Lists have several built-in methods for manipulation.

my_list = [3, 1, 4, 2, 5]

my_list.sort() # Sort the list in ascending order
print(my_list) # Output: [1, 2, 3, 4, 5]

my_list.reverse() # Reverse the order of the list
print(my_list) # Output: [5, 4, 3, 2, 1]

length = len(my_list) # Get the length of the list
print(length) # Output: 5