1. List
In Python, a “list” is a collection of values that are ordered and mutable (can be changed).
Here’s an example of a list of cars:
1 2 |
cars = ["Toyota", "Honda", "Ford", "BMW"] |
2. Tuple
A “tuple” is similar to a list in that it is a collection of values. However, tuples are ordered and immutable (cannot be changed). Tuples are defined using parentheses ()
instead of square brackets. Here’s an example of a tuple of cars:
1 2 |
cars = ("Toyota", "Honda", "Ford", "BMW") |
3. Dictionary
A “dictionary” is a collection of key-value pairs, where each key is unique. Dictionaries are defined using curly braces {}
. In the example below, each car name is the key and its corresponding value is a dictionary of specifications:
1 2 3 4 5 6 7 |
cars = { "Toyota": {"model": "Camry", "year": 2020}, "Honda": {"model": "Civic", "year": 2021}, "Ford": {"model": "Mustang", "year": 2022}, "BMW": {"model": "3 Series", "year": 2023} } |
In this example, you can access the information about a specific car by using its name as a key:
1 2 3 |
print(cars["Toyota"]) # Output: {"model": "Camry", "year": 2020} |
List, Tuple & Dictionary example in one code:
here’s an example that demonstrates the usage of lists, tuples, and dictionaries in the context of a car:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# A list to store multiple car names car_names = ["Toyota", "Honda", "BMW", "Mercedes"] # A tuple to store information of a specific car, such as its make, model, and year car_info = ("Toyota", "Camry", 2020) # A dictionary to store detailed information of the same car, such as its make, model, year, and features car_details = { "make": "Toyota", "model": "Camry", "year": 2020, "features": ["Bluetooth connectivity", "Rear camera", "Sunroof"] } # Accessing the information from the list, tuple, and dictionary print(f"Car names: {car_names}") print(f"Car information (make, model, year): {car_info}") print(f"Car details: {car_details}") |
When run, the code outputs:
1 2 3 4 |
Car names: ['Toyota', 'Honda', 'BMW', 'Mercedes'] Car information (make, model, year): ('Toyota', 'Camry', 2020) Car details: {'make': 'Toyota', 'model': 'Camry', 'year': 2020, 'features': ['Bluetooth connectivity', 'Rear camera', 'Sunroof']} |