In Python, a list is a built-in data structure that allows you to store and manipulate a collection of items. Lists are versatile and can hold elements of different data types. Here are some key features and operations related to lists:
# Creating an empty list
empty_list = []
# Creating a list with elements
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
mixed_list = [1, 'hello', 3.14, True]
# Accessing elements by index
first_element = numbers[0] # 1
last_element = numbers[-1] # 5
# Slicing
subset = numbers[1:4] # [2, 3, 4]
# Modifying elements
fruits[1] = 'grape' # ['apple', 'grape', 'orange']
# Adding elements
fruits.append('kiwi') # ['apple', 'grape', 'orange', 'kiwi']
fruits.insert(1, 'pear') # ['apple', 'pear', 'grape', 'orange', 'kiwi']
# Removing elements
fruits.remove('grape') # ['apple', 'pear', 'orange', 'kiwi']
popped_item = fruits.pop(2) # Removes and returns the element at index 2
# Length of a list
length = len(numbers) # 5
# Concatenation
combined_list = numbers + fruits
# Repetition
repeated_list = numbers * 3
# Sorting
numbers.sort() # Sorts the list in-place
sorted_numbers = sorted(numbers) # Returns a new sorted list
# Finding index
index_of_apple = fruits.index('apple')
# Count occurrences
count_of_apple = fruits.count('apple')
List comprehensions provide a concise way to create lists. They can include conditions and expressions.
squares = [x**2 for x in numbers]
even_numbers = [x for x in numbers if x % 2 == 0]
Lists can contain other lists, creating nested structures.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Lists are a fundamental and flexible data structure in Python, widely used in various programming scenarios. They offer a range of built-in methods and operations for efficient manipulation and processing of data.