SortedCoding
1.2K subscribers
185 photos
38 videos
194 files
140 links
Learn to code with clarity and precision
Download Telegram
Now, Let's move to the next topic in the Python Coding Challenge:

Lists & Tuples

🔹 What is a List?

A list is a mutable (changeable) collection of items in a specific order.

Syntax:

fruits = ["apple", "banana", "cherry"]

print(fruits[0]) # Output: apple

fruits.append("mango")

print(fruits) # Output: ['apple', 'banana', 'cherry', 'mango']

You can add, remove, or update elements in a list.


🔸 What is a Tuple?

A tuple is similar to a list, but it's immutable (unchangeable once defined).

Syntax:

colors = ("red", "green", "blue")
print(colors[1]) # Output: green

🔒 You cannot modify, append, or remove elements from a tuple after creation.


Key Differences:

Mutability:

- List: Mutable — you can change, add, or remove elements after creation.
- Tuple: Immutable — once defined, you cannot change, add, or remove elements.


Syntax:

- List: Use square brackets → []

my_list = [1, 2, 3]

- Tuple: Use round brackets → ()

my_tuple = (1, 2, 3)


Use Case:

- List: Use when you need to modify the collection later.

- Tuple: Use when the data should remain constant or to ensure integrity.

Performance:

Tuple is slightly faster than List due to immutability and fixed size.


🛠 Mini Project: Grocery List Manager

Let’s build a simple grocery list app where you can:

- Add items

- Remove items

- Display all items

Python Code:

grocery_list = []

while True:
print("\nOptions: add / remove / show / exit")
action = input("What would you like to do? ")

if action == "add":
item = input("Enter item to add: ")
grocery_list.append(item)
print(f"{item} added.")

elif action == "remove":
item = input("Enter item to remove: ")
if item in grocery_list:
grocery_list.remove(item)
print(f"{item} removed.")
else:
print("Item not found.")

elif action == "show":
print("Your grocery list:")
for i in grocery_list:
print("-", i)

elif action == "exit":
break

else:
print("Invalid option.")

Try running this and see how lists work in real time!


React with ❤️ once you’re ready for the quiz
1
what is the output of the following code ?
fruits = ["apple","banana","cherry"]
print(fruits[1])
Anonymous Quiz
29%
apple
67%
banana
0%
cherry
4%
None of the above
1
Q2. Which of these defines a tuple correctly?
Anonymous Quiz
30%
my_tuple = [1,2,3]
52%
my_tuple = (1,2,3)
17%
my_tuple = {1,2,3}
1
1
1
Which syntax creates an empty list?
Anonymous Quiz
61%
[]
14%
{}
21%
()
4%
set()
1
Today, let's move on to the next topic in the Python Coding Challenge:

Dictionaries & Sets 🔑🧺

🔹Day 5: What is a Dictionary in Python?

A dictionary is an unordered, mutable collection that stores data in key-value pairs.

🧠 Example:

student = {
"name": "Amit",
"age": 21,
"course": "Python"
}

print(student["name"]) # Output: Amit

- Keys must be unique and immutable (like strings, numbers).
- Values can be anything: strings, numbers, lists, or even other dictionaries.


🧰 Common Dictionary Methods:

student.get("age") # Returns 21
student.keys() # Returns all keys
student.values() # Returns all values
student.items() # Returns key-value pairs
student["grade"] = "A+" # Adds a new key-value pair


🔹 What is a Set in Python?

A set is an unordered collection of unique elements.

🧠 Example :

numbers = {1, 2, 3, 4, 4, 2}
print(numbers) # Output: {1, 2, 3, 4} — no duplicates

- Sets remove duplicates automatically.
- Useful for membership checks, uniqueness, and set operations (union, intersection).


Real-Life Project: Contact Book using Dictionary

- Build a CLI-based contact book where users can:
- Add new contacts (name, phone)
- View all contacts
- Search by name
- Delete a contact


💡 Python Code:

contacts = {}

while True:
print("\n1. Add Contact\n2. View All\n3. Search\n4. Delete\n5. Exit")
choice = input("Enter choice: ")

if choice == '1':
name = input("Name: ")
phone = input("Phone: ")
contacts[name] = phone
print("Contact saved!")

elif choice == '2':
for name, phone in contacts.items():
print(f"{name} : {phone}")

elif choice == '3':
name = input("Enter name to search: ")
if name in contacts:
print(f"{name}'s phone: {contacts[name]}")
else:
print("Contact not found.")

elif choice == '4':
name = input("Enter name to delete: ")
if name in contacts:
del contacts[name]
print("Deleted successfully.")
else:
print("No such contact.")

elif choice == '5':
break
else:
print("Invalid choice.")


React with ❤️ once you’re ready for the quiz
2
What will be the output of following code?

d = {"a": 1, "b": 2} print(d.get("c"))
Anonymous Quiz
7%
0
30%
Error
27%
None
37%
"c"
1
Which one of these is NOT allowed as a key in a dictionary?
Anonymous Quiz
21%
integer
14%
String
50%
Tuple
14%
List
2
Which method returns all key-value pairs in a dictionary?
Anonymous Quiz
32%
.Values()
18%
.get()
25%
.items()
25%
.keys()
1
What will this code output?

info = {"name": "Alex", "age": 25} info["city"] = "New York" print("info")
Anonymous Quiz
35%
{'name': 'Alex', 'age': 25, 'city': 'New York'}
26%
{'city': 'New York'}
21%
info
18%
Error
1
What will be the output of this code ?
s = {1,2,3,2,4}
print(len(s))
Anonymous Quiz
66%
5
26%
4
6%
3
3%
2
1
Today, Let’s move on to the next topic in the Python Coding Challenge:

🔹Day 6: Conditionals (if, elif, else)

In Python, conditional statements allow your code to make decisions.

💡 What Are Conditionals?

They help your program execute certain code blocks only when specific conditions are true.

Syntax :

if condition:
# Code runs if condition is True
elif another_condition:
# Runs if previous conditions were False, this one is True
else:
# Runs if none of the above conditions are True

🧠 Example :

age = 18

if age >= 18:
print("You’re an adult.")
elif age > 13:
print("You’re a teenager.")
else:
print("You’re a child.")

Output:

You’re an adult.


🎯 Mini Project: Guess the Number Game

Let’s build a small game using what we’ve learned so far:

Python Code

import random

number = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))

if guess == number:
print("🎉 Correct! You guessed it right.")
elif guess < number:
print("Too low! Try again.")
else:
print("Too high! Try again.")

print(f"The correct number was: {number}")


This project uses:

- if, elif, else
- User input
- Random module


React with ❤️ once you’re ready for the quiz
3