HomePYTHONLists, Tuples, Sets, and Dictionaries in Python

Lists, Tuples, Sets, and Dictionaries in Python

Lists, Tuples, Sets, and Dictionaries

🔹 1. LISTS

✅ Definition:

A list is an ordered, mutable (changeable) collection of elements.

✅ Syntax:

my_list = [1, 2, 3, 'apple', 4.5]

✅ Characteristics:

  • Ordered
  • Mutable
  • Allows duplicate values
  • Can contain mixed data types

✅ Basic Operations:

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

# Access elements
print(fruits[0])        # apple

# Update element
fruits[1] = 'mango'     # ['apple', 'mango', 'cherry']

# Append
fruits.append('orange')  # ['apple', 'mango', 'cherry', 'orange']

# Insert
fruits.insert(1, 'grape') # ['apple', 'grape', 'mango', 'cherry', 'orange']

# Remove
fruits.remove('cherry')   # ['apple', 'grape', 'mango', 'orange']

# Pop last item
fruits.pop()             # Removes 'orange'

# Length
len(fruits)

# Loop
for fruit in fruits:
    print(fruit)

🔹 2. TUPLES

✅ Definition:

A tuple is an ordered, immutable (unchangeable) collection.

✅ Syntax:

my_tuple = (1, 2, 3, 'apple', 4.5)

✅ Characteristics:

  • Ordered
  • Immutable
  • Allows duplicate values
  • Can contain mixed data types

✅ Basic Operations:

colors = ('red', 'green', 'blue')

# Access elements
print(colors[1])       # green

# Count occurrences
colors.count('red')

# Index of element
colors.index('blue')

# Loop
for color in colors:
    print(color)

Tuples are used when you want data integrity (not modified accidentally).


🔹 3. SETS

✅ Definition:

A set is an unordered collection of unique elements.

✅ Syntax:

my_set = {1, 2, 3, 'apple'}

✅ Characteristics:

  • Unordered
  • Mutable (but elements must be immutable)
  • No duplicates allowed

✅ Basic Operations:

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Add
set1.add(5)

# Remove
set1.remove(2)

# Union
print(set1.union(set2))     # {1, 2, 3, 4, 5, 6}

# Intersection
print(set1.intersection(set2))  # {3, 4}

# Difference
print(set1.difference(set2))    # Elements only in set1

# Loop
for item in set1:
    print(item)

Sets are useful for removing duplicates and set operations.


🔹 4. DICTIONARIES

✅ Definition:

A dictionary is an unordered collection of key-value pairs.

✅ Syntax:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

✅ Characteristics:

  • Unordered (Python 3.6+ maintains insertion order)
  • Keys must be unique and immutable
  • Values can be any type

✅ Basic Operations:

person = {
    'name': 'John',
    'age': 30,
    'city': 'Mumbai'
}

# Access value
print(person['name'])       # John

# Update value
person['age'] = 35

# Add new key-value
person['profession'] = 'Engineer'

# Delete key
del person['city']

# Loop keys
for key in person:
    print(key, person[key])

# Loop items
for key, value in person.items():
    print(f"{key}: {value}")

# Get with default
print(person.get('salary', 'Not Available'))

Dictionaries are perfect for structured data, JSON-like objects, and fast lookups.


🔹 Summary Table

FeatureListTupleSetDictionary
Ordered✅ (3.7+)
Mutable
DuplicatesKeys ❌, Values ✅
IndexingKeys
Use CaseGeneral dataFixed dataUnique itemsKey-Value data

✅ Real-World Example

# Store student info with subjects
student = {
    'name': 'Ravi',
    'age': 21,
    'subjects': ['Math', 'Science'],
    'marks': {'Math': 90, 'Science': 85}
}

# Add subject
student['subjects'].append('English')

# Update marks
student['marks']['English'] = 88

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *