Python Lists
A list in Python is a collection of items separated by commas and enclosed within square brackets []
.
1. Creating Lists
You can create lists containing any data type, including numbers, strings, or even other lists.
Example:
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
mixed_list = [1, 'apple', True, 3.14]
2. Accessing Elements
You can access individual elements of a list using indexing.
Example:
numbers = [1, 2, 3, 4, 5]
first_element = numbers[0] # 1
last_element = numbers[-1] # 5
3. Slicing Lists
You can extract a sublist from a list using slicing.
Example:
numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4] # [2, 3, 4]
4. Modifying Lists
Lists are mutable, meaning you can modify their elements.
Example:
numbers = [1, 2, 3, 4, 5]
numbers[2] = 10 # [1, 2, 10, 4, 5]
5. List Methods
Python provides several methods to work with lists, such as append()
, insert()
, remove()
, pop()
, sort()
, reverse()
, and more.
Example:
fruits = ['apple', 'banana', 'orange']
fruits.append('grape')
fruits.insert(1, 'kiwi')
fruits.remove('banana')
popped = fruits.pop()
fruits.sort()
fruits.reverse()
Conclusion
Lists are versatile data structures in Python that allow you to store and manipulate collections of items. Understanding how to create, access, modify, and use list methods is essential for working with lists effectively.