Table of contents
- Difference between Lists, Tuples and Sets:
- ✔️Create a Dictionary and use Dictionary methods to print your favorite tool just by using the keys of the Dictionary.
- ✔️ Create a List of cloud service providers eg. cloud_providers = ["AWS", "GCP", "Azure"]
- Write a program to add Digital Ocean to the list of cloud_providers and sort the list in alphabetical order.
Difference between Lists, Tuples and Sets:
Lists:
Lists are mutable, which means their elements can be modified.
Elements in a list are ordered and can be accessed using indices.
Lists allow duplicate elements.
Lists are created using square brackets
[ ]
or thelist()
constructor.
Tuples:
Tuples are immutable, meaning their elements cannot be modified after creation.
Elements in a tuple are ordered and can be accessed using indices.
Tuples allow duplicate elements.
Tuples are created using parentheses
( )
or thetuple()
constructor.
Sets:
Sets are mutable and unordered collections of unique elements.
Sets do not allow duplicate elements.
Sets do not have indices, so you cannot access elements by indices.
Sets are useful for mathematical operations like union, intersection, and difference.
Sets are created using curly braces
{ }
or theset()
constructor.
Here are some examples to illustrate the differences:
pythonCopy code# List example
fruits = ["apple", "banana", "orange", "apple"]
fruits[0] = "grape" # Modifying an element
print(fruits) # Output: ["grape", "banana", "orange", "apple"]
# Tuple example
colors = ("red", "green", "blue")
# colors[0] = "yellow" # Error: Tuples are immutable
# Set example
numbers = {1, 2, 3, 3, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}
✔️Create a Dictionary and use Dictionary methods to print your favorite tool just by using the keys of the Dictionary.
step 1: To create a dictionary and print your favorite tool
fav_tools = {
1: "Linux",
2: "Git",
3: "Docker",
4: "Kubernetes",
5: "Terraform",
6: "Ansible",
7: "Chef"
}
step 2: Get the key of your favorite tool:
favorite_tool_key = int(input("What is your favorite tool? (1-7): "))
step 3: Get the value of your favorite tool:
favorite_tool = fav_tools[favorite_tool_key]
step 4: Print the favorite tool:
print("Your favorite tool is {favorite_tool}")
The output will be:
What is your favorite tool? (1-7): 4
Your favorite tool is Kubernetes
✔️ Create a List of cloud service providers eg. cloud_providers = ["AWS", "GCP", "Azure"]
Write a program to add Digital Ocean
to the list of cloud_providers and sort the list in alphabetical order.
step 1: create a list with the above-mentioned strings
cloud_providers = ["AWS", "GCP", "Azure"]
step 2: Now add Digital ocean
cloud_providers.append("Digital Ocean")
step 3: Now sort the list in alphabetical order
cloud_providers.sort()
step 4: Now print the list
print(cloud_providers)
The output will be as follows
['AWS', 'Azure', 'Digital Ocean', 'GCP']
For another Python-related blog.
Follow me on LinkedIn to see interesting posts like this : )