Data Types: Lists, Tuples, Dictionaries#

In this notebook, we’ll explore three important data types in Python: lists, tuples, and dictionaries. These data structures allow us to store and organize multiple pieces of information in different ways.

Lists#

Lists are ordered, mutable sequences of elements. Let’s create a simple list and examine its properties.

fruits = ['apple', 'banana', 'cherry']
print(fruits)
['apple', 'banana', 'cherry']

Lists are mutable, which means we can modify them after creation. Let’s add an element to our list.

fruits.append('date')
print(fruits)
['apple', 'banana', 'cherry', 'date']

We can access elements in a list using their index. Remember, Python uses 0-based indexing.

print(fruits[0])  # First element
print(fruits[-1])  # Last element
apple
date

Tuples#

Tuples are similar to lists, but they are immutable. Once created, they cannot be modified. Let’s create a tuple and try to modify it.

coordinates = (10, 20)
print(coordinates)
(10, 20)

If we try to modify a tuple, Python will raise an error. Uncomment the following line to see the error.

# coordinates[0] = 15  # This will raise a TypeError

Dictionaries#

Dictionaries are unordered collections of key-value pairs. They are mutable and allow fast lookups. Let’s create a simple dictionary.

person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(person)
{'name': 'Alice', 'age': 30, 'city': 'New York'}

We can access values in a dictionary using their keys.

print(person['name'])
print(person['age'])
Alice
30

Dictionaries are mutable, so we can add or modify key-value pairs.

person['job'] = 'Engineer'
person['age'] = 31
print(person)
{'name': 'Alice', 'age': 31, 'city': 'New York', 'job': 'Engineer'}

Summary#

In this notebook, we’ve explored three important data types in Python:

  • Lists: ordered, mutable sequences

  • Tuples: ordered, immutable sequences

  • Dictionaries: unordered, mutable collections of key-value pairs

Each of these data types has its own use cases and advantages, making them essential tools in Python programming.