Mastering Lists, Tuples, and Dictionaries
Working with Lists
Accessing and Modifying List Elements
You can access individual elements in a list using their index, which starts from 0. Lists are mutable, so you can modify, add, or remove elements as needed.
my_list = [1, 2, 3, 'four', 5.0]
print(my_list[2]) ## Output: 3
my_list[3] = 'four_updated'
my_list.append(6)
del my_list[0]
List Operations and Methods
Python provides a wide range of list operations and methods, such as slicing, concatenation, sorting, and more. These allow you to perform various data manipulation tasks.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) ## Output: [2, 3, 4]
new_list = my_list + [6, 7, 8]
my_list.sort(reverse=True)
Exploring Tuples
Tuple Basics
Tuples are immutable, meaning you cannot modify their elements after creation. They are often used to represent a collection of related data, such as coordinates or key-value pairs.
my_tuple = (1, 2.3, 'three')
print(my_tuple[1]) ## Output: 2.3
Tuple Unpacking
Tuple unpacking allows you to assign the elements of a tuple to individual variables, making it easier to work with the data.
point = (3.4, 5.2)
x, y = point
print(x) ## Output: 3.4
print(y) ## Output: 5.2
Mastering Dictionaries
Dictionary Basics
Dictionaries are unordered collections of key-value pairs. They allow you to store and retrieve data quickly using unique keys.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict['name']) ## Output: 'John'
Dictionary Operations and Methods
Dictionaries provide a variety of operations and methods for manipulating data, such as adding, modifying, and removing key-value pairs, as well as iterating over the keys or values.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict['age'] = 31
my_dict['country'] = 'USA'
del my_dict['city']
for key in my_dict:
print(key, my_dict[key])
By mastering the techniques for working with lists, tuples, and dictionaries, you will be able to effectively organize and manipulate data in your Python programs. The next section will explore advanced data manipulation techniques using these built-in data structures.