Data Structures in Python


  • Lists

Lists are ordered, mutable collections that allow duplicate values. They are widely used because of their flexibility.


  1. Creating Lists

Lists can be created using square brackets or the list() function.

numbers = [1, 2, 3, 4]
names = ["Pooja", "Nayana"]
mixed = [1, "Hello", 3.5]data = list((10, 20, 30))

Key Points

  • Can store different data types
  • Maintain insertion order
  • Allow duplicate values

2. List Operations

Lists support many operations:

a = [1, 2, 3]
b = [4, 5]print(a + b)     # Concatenation → [1,2,3,4,5]
print(a * 2)     # Repetition → [1,2,3,1,2,3]
print(a[0])      # Indexing → 1
print(a[-1])     # Last element → 3
print(a[0:2])    # Slicing → [1,2]

Membership Check

print(2 in a)  # True

3. List Methods

Lists provide built-in methods for modification:

nums = [3, 1, 2]nums.append(4)        # Add element at end
nums.insert(1, 10)    # Insert at index
nums.remove(1)        # Remove element
nums.pop()            # Remove last element
nums.sort()           # Sort ascending
nums.reverse()        # Reverse list

//Additional Methods

nums.count(2)     # Count occurrences
nums.index(3)     # Find index
nums.copy()       # Copy list
nums.clear()      # Remove all elements

4. List Comprehensions

List comprehensions provide a concise way to create lists.

squares = [x**2 for x in range(5)]

With Condition

even = [x for x in range(10) if x % 2 == 0]

Nested Comprehension

pairs = [(x, y) for x in range(2) for y in range(2)]

Advantages

  • Shorter code
  • Faster execution
  • More readable

  • Tuples

Tuples are ordered and immutable collections. Once created, they cannot be modified.


1. Creating Tuples

t = (1, 2, 3)
single = (5,)
t2 = 1, 2, 3

Key Points

  • Immutable
  • Faster than lists
  • Used for fixed data

2. Tuple Operations

t = (10, 20, 30)print(t[0])        # Indexing
print(t[-1])       # Last element
print(t[1:3])      # Slicing
print(len(t))      # Length

//Tuple Packing and Unpacking

a, b, c = t
print(a, b, c)

3. Tuple vs List

FeatureListTuple
MutabilityMutableImmutable
Syntax[]()
PerformanceSlowerFaster
MemoryMoreLess
Use CaseDynamic dataFixed data

  • Sets

Sets are unordered collections that store unique elements only.


1. Creating Sets

s = {1, 2, 3}
s2 = set([1, 2, 2, 3])  # Removes duplicates

Empty Set

s = set()

2. Set Operations

a = {1, 2, 3}
b = {2, 3, 4}print(a | b)   # Union → {1,2,3,4}
print(a & b)   # Intersection → {2,3}
print(a - b)   # Difference → {1}
print(a ^ b)   # Symmetric difference → {1,4}

//Subset and Superset

print(a.issubset(b))
print(a.issuperset(b))

3. Set Methods

s = {1, 2}s.add(3)
s.update([4, 5])
s.remove(2)
s.discard(10)   # No error if not found
s.clear()

  • Dictionaries

Dictionaries store data as key-value pairs and are widely used for structured data.


1. Creating Dictionaries

student = {"name": "Pooja", "age": 20}
data = dict(a=1, b=2)

//Nested Dictionary

student = {
    "name": "Pooja",
    "marks": {"math": 90, "science": 85}
}

2. Accessing Values

print(student["name"])
print(student.get("age"))

//Adding/Updating Values

student["age"] = 21
student["city"] = "Mysore"

3. Dictionary Methods

student.keys()
student.values()
student.items()student.update({"age": 22})
student.pop("name")
student.popitem()
student.clear()

4. Iterating Through Dictionaries

for key in student:
print(key)for value in student.values():
print(value)for key, value in student.items():
print(key, value)

Example

for key, value in student.items():
    print(f"{key}: {value}")

Conclusion

Data structures are the backbone of Python programming. Lists, tuples, sets, and dictionaries each serve specific purposes and provide different ways to store and manipulate data.

Lists are flexible and widely used, tuples are efficient for fixed data, sets are ideal for unique elements, and dictionaries are powerful for key-value mapping. By mastering these data structures, learners can handle complex data efficiently and build scalable, real-world applications.

A strong understanding of data structures is essential for advancing into algorithms, data science, and software development.

Comments

Leave a Reply

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