Python Lists


In Python, lists are one of the most versatile and widely used data structures. A list allows you to store multiple items in a single variable. Unlike strings, which can only hold text, lists can store items of different data types, including numbers, strings, and even other lists. Understanding lists is essential for working efficiently with Python.

This tutorial will cover everything about Python lists, including creation, accessing elements, modifying lists, built-in methods, and practical examples.

What is a List in Python?

A list in Python is an ordered collection of items enclosed in square brackets [] and separated by commas. Lists can contain items of any data type and can even include other lists, making them highly flexible.

Example:

fruits = ["Apple", "Banana", "Cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = ["Emma", 25, True, 5.5]
nested_list = [1, [2, 3], [4, 5, 6]]

In these examples:

  • fruits contains strings.

  • numbers contains integers.

  • mixed_list combines strings, numbers, and boolean values.

  • nested_list contains lists within a list.

Creating Lists in Python

You can create a list in multiple ways:

  1. Using Square Brackets:

colors = ["Red", "Green", "Blue"]
  1. Using the list() Function:

numbers = list((1, 2, 3, 4))
print(numbers)  # Output: [1, 2, 3, 4]
  1. Empty List:

empty_list = []

Accessing Elements in a List

Each item in a list has an index, starting from 0. You can access elements using square brackets [].

fruits = ["Apple", "Banana", "Cherry"]
print(fruits[0])  # Output: 'Apple'
print(fruits[2])  # Output: 'Cherry'

Negative indexing allows you to access elements from the end of the list:

print(fruits[-1])  # Output: 'Cherry'
print(fruits[-2])  # Output: 'Banana'

Slicing Lists

Slicing allows you to access a range of elements using the syntax start:stop:step.

numbers = [1, 2, 3, 4, 5, 6, 7]
print(numbers[0:4])   # Output: [1, 2, 3, 4]
print(numbers[3:])    # Output: [4, 5, 6, 7]
print(numbers[:5])    # Output: [1, 2, 3, 4, 5]
print(numbers[::2])   # Output: [1, 3, 5, 7] (every second element)

Modifying Lists

Lists are mutable, meaning you can change their content after creation.

  1. Changing an Element:

fruits = ["Apple", "Banana", "Cherry"]
fruits[1] = "Orange"
print(fruits)  # Output: ['Apple', 'Orange', 'Cherry']
  1. Adding Elements:

  • append() – adds a single item at the end:

fruits.append("Mango")
  • insert() – inserts an item at a specific index:

fruits.insert(1, "Kiwi")  # Insert at index 1
  • extend() – adds multiple items at once:

fruits.extend(["Pineapple", "Grapes"])
  1. Removing Elements:

  • remove() – removes an item by value:

fruits.remove("Apple")
  • pop() – removes an item by index:

fruits.pop(2)  # Removes item at index 2
  • clear() – removes all elements:

fruits.clear()

List Operations

Python allows several operations with lists:

  1. Concatenation – combining lists:

list1 = [1, 2]
list2 = [3, 4]
result = list1 + list2
print(result)  # Output: [1, 2, 3, 4]
  1. Repetition – repeating a list:

numbers = [1, 2]
print(numbers * 3)  # Output: [1, 2, 1, 2, 1, 2]
  1. Membership – checking if an item exists:

fruits = ["Apple", "Banana"]
print("Apple" in fruits)   # Output: True
print("Mango" not in fruits)  # Output: True

Built-in List Methods

Python provides many built-in methods for lists:

  • index() – returns the index of the first matching value:

fruits = ["Apple", "Banana", "Cherry"]
print(fruits.index("Banana"))  # Output: 1
  • count() – counts occurrences of an item:

numbers = [1, 2, 2, 3, 2]
print(numbers.count(2))  # Output: 3
  • sort() – sorts the list in ascending order:

numbers = [3, 1, 4, 2]
numbers.sort()
  • reverse() – reverses the list:

numbers.reverse()

Nested Lists

A nested list is a list inside another list. You can access items using multiple indices:

nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list[1][0])  # Output: 3

Nested lists are useful for creating matrices or structured data.

Practical Examples with Lists

  1. Sum of Elements:

numbers = [10, 20, 30]
total = sum(numbers)
print(total)  # Output: 60
  1. Finding Maximum and Minimum:

numbers = [10, 20, 30]
print(max(numbers))  # Output: 30
print(min(numbers))  # Output: 10
  1. Iterating through a List:

fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
    print(fruit)
  1. Copying a List:

fruits_copy = fruits.copy()
  1. Removing Duplicates:

numbers = [1, 2, 2, 3, 3, 4]
unique_numbers = list(set(numbers))

Summary of the Tutorial

Python lists are flexible, ordered, and mutable, making them ideal for storing collections of items. They support indexing, slicing, and various operations, including adding, removing, and modifying elements. Lists are the foundation for many Python programs, and mastering them will make it easier to work with other data structures like tuples, dictionaries, and sets.


Practice Questions

  1. Create a list of your five favorite fruits and print it.

  2. Access and print the first and last elements of the list numbers = [10, 20, 30, 40, 50].

  3. Using the list colors = ["Red", "Green", "Blue"], add "Yellow" to the end of the list.

  4. Insert "Orange" at index 1 in the list fruits = ["Apple", "Banana", "Cherry"].

  5. Remove the element "Banana" from the list fruits = ["Apple", "Banana", "Cherry"].

  6. Combine the lists [1, 2, 3] and [4, 5, 6] into a single list.

  7. Count how many times the number 2 appears in the list numbers = [1, 2, 2, 3, 2, 4].

  8. Sort the list numbers = [5, 2, 9, 1, 7] in ascending order.

  9. Reverse the list fruits = ["Apple", "Banana", "Cherry"].

  10. Access the element 4 from the nested list matrix = [[1, 2], [3, 4], [5, 6]].


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top