Python journey | Day 5
Lists and tuples are ordered collections in Python. Lists are mutable, allowing modifications, while tuples are immutable. Both support indexing, slicing, and various modification methods. Dictionaries store data as key-value pairs, ideal for quick retrieval. They offer operations to add, remove, or access elements using keys. Understanding these data structures—lists for flexibility, tuples for immutability, and dictionaries for key-based storage—is fundamental for efficient Python programming.
Here's an overview of the fundamental operations and features of lists, tuples, and dictionaries in Python:
Lists and Tuples:
Lists:
Lists are ordered, mutable (changeable), and can contain elements of different types.
Indexing: Access elements using their position (index) in the list. Indexing starts at 0.
my_list = [3, 7, 12, 'apple', 'banana']
print(my_list[0]) # Output: 3
print(my_list[3]) # Output: apple
Slicing: Extract subparts of a list using start, end, and step values.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]
print(my_list[::2]) # Output: [1, 3, 5]
Modifying methods:
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Adds 6 to the end
my_list.insert(2, 'hello') # Inserts 'hello' at index 2
my_list.remove(3) # Removes the first occurrence of 3
my_list.pop() # Removes and returns the last element
my_list.reverse() # Reverses the list in place
Tuples:
Tuples are ordered, immutable sequences, commonly used to store collections of heterogeneous data.
my_tuple = (1, 2, 'a', 'b')
print(my_tuple[2]) # Output: a
print(my_tuple[:2]) # Output: (1, 2)
Dictionaries:
Dictionaries are unordered collections of data in key-value pairs.
Key-Value Pairs:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(my_dict['age']) # Output: 30
Operations and methods:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
my_dict['email'] = '[email protected]' # Adding a new key-value pair
del my_dict['city'] # Removing 'city' key
my_dict.pop('age') # Removes and returns the value of 'age'
my_dict.keys() # Returns all keys in the dictionary
my_dict.values() # Returns all values in the dictionary
Dictionaries are highly flexible and versatile for storing and retrieving data based on keys. Lists and tuples, on the other hand, are primarily used to store sequences of items, with tuples being immutable while lists are mutable.