Introduction

Lists are a fundamental data structure in Python used to store ordered collections of items. In this guide, we'll explore the basics of Python lists and various operations for working with ordered data.


Creating Lists

You can create lists in Python by enclosing items in square brackets and separating them with commas. For example:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]

Accessing List Items

You can access individual items in a list by their index, starting from 0. Negative indices count from the end of the list. For example:

fruits = ["apple", "banana", "cherry"]
first_fruit = fruits[0] # "apple"
last_fruit = fruits[-1] # "cherry"

Modifying Lists

You can modify lists by changing their items, appending new items, or removing items. Some common list operations include:

  • append(): Adds an item to the end of the list.
  • insert(): Inserts an item at a specific index.
  • remove(): Removes a specific item by value.
  • pop(): Removes and returns an item by index.

For example:

fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits.insert(1, "grape")
fruits.remove("banana")
removed_fruit = fruits.pop(2)

List Slicing

List slicing allows you to create new lists by extracting a portion of an existing list. Slicing uses a colon to specify a range. For example:

numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4] # [2, 3, 4]

List Comprehensions

List comprehensions are a concise way to create new lists by applying an expression to each item in an existing list. For example:

numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]

Conclusion

Python lists are versatile and widely used for storing and manipulating ordered data. Understanding lists and their operations is essential for many Python applications, from simple data storage to complex data processing.