Python Lesson 6: Lists

PYTHON

AllComputerss

4/18/20261 min read

python tutorials
python tutorials

Lists are one of the most versatile and commonly used data structures in Python. They allow you to store multiple items in a single variable, making it easy to organize and manipulate collections of data.

Creating Lists

You can create a list by placing items inside square brackets [], separated by commas.

# Example of a list

fruits = ["apple", "banana", "cherry"]

print(fruits)

Accessing List Items

Lists are ordered, meaning each item has an index starting from 0.

print(fruits[0]) # Output: apple

print(fruits[1]) # Output: banana

You can also use negative indexing to access items from the end:

print(fruits[-1]) # Output: cherry

Slicing Lists

You can extract a portion of a list using slicing:

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

Modifying Lists

Lists are mutable, meaning you can change their contents:

fruits[1] = "blueberry"

print(fruits) # Output: ['apple', 'blueberry', 'cherry']

Common List Methods

Python provides many built-in methods to work with lists:

numbers = [1, 2, 3]

numbers.append(4) # Add item to the end

numbers.insert(1, 5) # Insert item at index 1

numbers.remove(2) # Remove the first occurrence of 2

numbers.sort() # Sort the list

print(numbers) # Output: [1, 3, 4, 5]

Iterating Through Lists

You can loop through a list to access each item:

for fruit in fruits:

print(fruit)

Nested Lists

Lists can contain other lists, allowing you to create complex structures:

matrix = [[1, 2], [3, 4], [5, 6]]

print(matrix[0]) # Output: [1, 2]

print(matrix[0][1]) # Output: 2

Conclusion

Lists are a powerful tool in Python for handling collections of data. Their flexibility and wide range of built-in methods make them essential for everyday programming tasks. Mastering lists will prepare you for more advanced data structures like tuples, sets, and dictionaries.

© 2026 AllComputerss. All rights reserved.