python Data Structures
Data structures Python programming mein bahut important hote hain kyunki ye data ko organize aur manipulate karne ka efficient tareeka provide karte hain. Yahan kuch popular data structures ke concepts aur unke examples Python code ke saath diye gaye hain:
1. Lists:
Lists Python mein ordered collections hote hain jo heterogeneous data types ko store kar sakte hain.
python
# Creating a list
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(numbers[0]) # Output: 1
print(fruits[1]) # Output: banana
# Modifying elements
fruits[2] = "orange"
print(fruits) # Output: ['apple', 'banana', 'orange']
# List methods
fruits.append("pear")
print(fruits) # Output: ['apple', 'banana', 'orange', 'pear']
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'pear']
# List slicing
print(numbers[1:4]) # Output: [2, 3, 4]
2. Tuples:
Tuples immutable hoti hain, matlab unki values change nahi hoti hain once ye create ho jaati hain.
python
# Creating a tuple
coordinates = (3, 5)
# Accessing elements
print(coordinates[0]) # Output: 3
print(coordinates[1]) # Output: 5
# Tuples are immutable
# coordinates[0] = 4 # Error: 'tuple' object does not support item assignment
3. Dictionaries:
Dictionaries key-value pairs ko store karte hain aur fast access provide karte hain.
python
# Creating a dictionary
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Accessing values
print(person["name"]) # Output: John
print(person["age"]) # Output: 30
# Modifying values
person["age"] = 35
print(person) # Output: {'name': 'John', 'age': 35, 'city': 'New York'}
# Dictionary methods
person["job"] = "Developer"
print(person) # Output: {'name': 'John', 'age': 35, 'city': 'New York', 'job': 'Developer'}
# Iterating through keys and values
for key in person:
print(key, person[key])
# Check if key exists
if "city" in person:
print("City:", person["city"])
4. Sets:
Sets unique elements ko store karte hain aur mathematical set operations provide karte hain.
python
# Creating a set
unique_numbers = {1, 2, 3, 4, 3, 2, 1}
print(unique_numbers) # Output: {1, 2, 3, 4}
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
5. Stacks and Queues:
Stacks (Last In First Out) aur queues (First In First Out) data ko organize karne ke liye use hoti hain.
python
# Stack using list
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop()) # Output: 3
# Queue using collections.deque
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)
print(queue.popleft()) # Output: 1
Yeh data structures Python mein commonly use hoti hain aur inka efficient use karke programming tasks ko simplify kiya ja sakta hai. In data structures ka understanding Python programming ke liye crucial hota hai.