1. Shopping List Program
shopping_list = ['milk', 'bread', 'eggs']
Explanation
- A list is used to store multiple items.
-
shopping_listis the variable name. -
The list contains:
- milk
- bread
- eggs
So the list looks like:
['milk', 'bread', 'eggs']
shopping_list.append('butter')
Explanation
-
append()is used to add a new item at the end of the list. -
Here,
"butter"is added.
Now the list becomes:
['milk', 'bread', 'eggs', 'butter']
print(shopping_list)
Explanation
-
print()displays output on the screen.
Output:
['milk', 'bread', 'eggs', 'butter']
shopping_list.remove('bread')
Explanation
-
remove()deletes an item from the list. -
Here,
"bread"is removed.
Now the list becomes:
['milk', 'eggs', 'butter']
print(shopping_list)
Explanation
This prints the updated list.
Output:
['milk', 'eggs', 'butter']
2. Dictionary of Countries and Capitals
countries_capitals = {
'USA': 'Washington, D.C.',
'France': 'Paris',
'Japan': 'Tokyo',
'Germany': 'Berlin',
'Brazil': 'Brasília'
}
Explanation
- A dictionary stores data in key : value pairs.
-
Here:
- Country = Key
- Capital = Value
Example:
'USA': 'Washington, D.C.'
means:
- USA is the country
- Washington, D.C. is its capital
The dictionary stores 5 countries and their capitals.
print(countries_capitals)
Explanation
This prints the complete dictionary.
Output:
{
'USA': 'Washington, D.C.',
'France': 'Paris',
'Japan': 'Tokyo',
'Germany': 'Berlin',
'Brazil': 'Brasília'
}
3. Finding Common Elements Using Set
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
Explanation
Two lists are created.
-
list1contains:[1, 2, 3, 4, 5] -
list2contains:[4, 5, 6, 7, 8]
common_elements = set(list1) & set(list2)
Explanation
Step 1: Convert lists into sets
set(list1)
becomes:
{1, 2, 3, 4, 5}
and
set(list2)
becomes:
{4, 5, 6, 7, 8}
Step 2: Find common values
The symbol & means intersection in sets.
It finds values present in both sets.
Common values are:
{4, 5}
So:
common_elements = {4, 5}
print(common_elements)
Explanation
This prints the common elements.
Output:
{4, 5}
Final Output of Whole Program
['milk', 'bread', 'eggs', 'butter']
['milk', 'eggs', 'butter']
{'USA': 'Washington, D.C.', 'France': 'Paris', 'Japan': 'Tokyo', 'Germany': 'Berlin', 'Brazil': 'Brasília'}
{4, 5}
Simple Concepts Used
| Concept | Purpose |
|---|---|
List [] | Store multiple items |
append() | Add item to list |
remove() | Remove item from list |
Dictionary {} | Store key-value pairs |
Set set() | Store unique values |
& operator | Find common elements |
print() | Display output |
Discussion (0)