Data Structures
Data structures are used to store and organize data in Python. There are several built-in data structures in Python, including lists, tuples, sets, and dictionaries.
Lists are ordered and mutable collections of items. They are enclosed in square brackets
[]
and can contain elements of different types. Lists allow indexing and slicing.Tuples are ordered and immutable collections of items. They are enclosed in parentheses
()
and can contain elements of different types. Tuples allow indexing and slicing.Sets are unordered and mutable collections of unique items. They are enclosed in curly braces
{}
or created using theset()
function. Sets do not allow duplicate elements.Dictionaries are unordered and mutable collections of key-value pairs. They are enclosed in curly braces
{}
and consist of keys and their corresponding values. Dictionaries allow fast lookup and retrieval of values based on their keys.
Here's an example that demonstrates creating, accessing, modifying, and adding elements to these data structures:
{{code}}
xxxxxxxxxx
print(person) # Output: {'name': 'John', 'age': 35, 'city': 'New York'}
# Creating a list
numbers = [1, 2, 3, 4, 5]
# Accessing elements in a list
print(numbers[0]) # Output: 1
# Modifying elements in a list
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4, 5]
# Appending elements to a list
numbers.append(6)
print(numbers) # Output: [1, 2, 10, 4, 5, 6]
# Creating a tuple
fruits = ('apple', 'banana', 'cherry')
# Accessing elements in a tuple
print(fruits[1]) # Output: banana
# Creating a set
colors = {'red', 'green', 'blue'}
# Adding elements to a set
colors.add('yellow')
print(colors) # Output: {'blue', 'red', 'yellow', 'green'}
# Creating a dictionary
person = {'name': 'John', 'age': 30, 'city': 'New York'}