List

 

Introduction

In Python, a List is a collection that allows us to store multiple items in a single variable. Lists are one of the most commonly used data types because they are flexible, ordered, and mutable.

Example:

fruits = ["apple", "banana", "cherry"] print(fruits)

Features of Lists

  • Ordered: Items have a defined order.

  • Mutable: We can change items after creating a list.

  • Allow duplicates: Lists can store repeated values.

  • Store multiple data types: A single list can hold strings, numbers, and even other lists.

Example:

mixed = [10, "Python", 3.14, True, [1, 2, 3]] print(mixed)

Creating a List

# Empty list empty_list = [] # List of numbers numbers = [1, 2, 3, 4, 5] # List of strings languages = ["Python", "C", "Java"]

Accessing List Items

We can access items using indexing and slicing.

fruits = ["apple", "banana", "cherry"] print(fruits[0]) # apple print(fruits[-1]) # cherry print(fruits[0:2]) # ['apple', 'banana']

Modifying a List

fruits = ["apple", "banana", "cherry"] fruits[1] = "mango" print(fruits) # ['apple', 'mango', 'cherry']

Adding Items

fruits = ["apple", "banana"] fruits.append("cherry") # add at end fruits.insert(1, "mango") # add at index print(fruits)

Removing Items

fruits = ["apple", "banana", "cherry"] fruits.remove("banana") # remove by value fruits.pop(0) # remove by index del fruits[0] # delete specific item print(fruits)

List Functions and Methods

Some common ones are:

  • len(list) → length of list

  • min(list), max(list) → smallest/largest element

  • sum(list) → sum of numeric values

  • list.sort() → sort list

  • list.reverse() → reverse list

Example:

numbers = [5, 2, 9, 1] numbers.sort() print(numbers) # [1, 2, 5, 9]

Looping Through a List

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

List Comprehension

A short way to create lists.

squares = [x**2 for x in range(5)] print(squares) # [0, 1, 4, 9, 16]

Nested Lists

Lists inside another list.

matrix = [[1, 2], [3, 4], [5, 6]] print(matrix[1][0]) # 3







Conclusion

Python Lists are powerful and versatile. They allow easy data storage, modification, and access. Understanding lists is essential for mastering Python programming.

Comments

Popular Posts