Lists in Python
Lists are one of the most commonly used data structures in Python. They are ordered, mutable (changeable), and allow duplicate elements. Lists are defined by placing items inside square brackets []
, separated by commas.
Creating a List:
You can create a list by placing a comma-separated sequence of items inside square brackets. Lists can contain elements of different data types, including integers, strings, and even other lists.
# Creating a list of fruits
fruits = ["apple", "banana", "cherry"]
# Lists can contain items of different data types
mixed_list = [1, "apple", True, 3.14]
# Empty list
empty_list = []
Accessing List Items:
You can access list items by referring to the index number, starting from 0 for the first item. Negative indexing allows you to start from the end of the list.
# Accessing list items
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
Modifying List Items:
Since lists are mutable, you can change the value of specific items by accessing them through their index.
# Changing the value of an item
fruits[1] = "blueberry"
print(fruits) # Output: ["apple", "blueberry", "cherry"]
Adding Items to a List:
You can add items to a list using methods like append()
, insert()
, or extend()
:
# Append an item to the end of the list
fruits.append("date")
print(fruits) # Output: ["apple", "blueberry", "cherry", "date"]
# Insert an item at a specific index
fruits.insert(1, "banana")
print(fruits) # Output: ["apple", "banana", "blueberry", "cherry", "date"]
# Extend the list by appending elements from another list
fruits.extend(["elderberry", "fig"])
print(fruits) # Output: ["apple", "banana", "blueberry", "cherry", "date", "elderberry", "fig"]
Removing Items from a List:
You can remove items from a list using methods like remove()
, pop()
, or clear()
:
# Remove a specific item by value
fruits.remove("blueberry")
print(fruits) # Output: ["apple", "banana", "cherry", "date", "elderberry", "fig"]
# Remove an item by index and return it
popped_item = fruits.pop(2)
print(popped_item) # Output: cherry
print(fruits) # Output: ["apple", "banana", "date", "elderberry", "fig"]
# Clear all items from the list
fruits.clear()
print(fruits) # Output: []
List Comprehension:
List comprehension offers a concise way to create lists. It is generally more compact and faster than traditional loops.
# Create a list of squares
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Lists are versatile and powerful, allowing you to store and manipulate collections of items easily. Mastering list operations is key to efficient Python programming.
Import Links
Here are some useful import links for further reading: