write in a .single .py file topic is "List operation in python from basic to very…
- User
write in a .single .py file topic is "List operation in python from basic to very advanced"
- Assistant
write in a .single .py file topic is "List operation in python from basic to very advanced"
Certainly! Below is a comprehensive Python script (list_operations.py) that covers list operations in Python from basic to very advanced levels. This script includes detailed explanations, examples, and demonstrations of various list functionalities.
# list_operations.py
"""
List Operations in Python: From Basic to Very Advanced
This script demonstrates various list operations in Python, ranging from basic manipulations
to advanced techniques. Each section includes explanations and examples.
"""
def basic_operations():
print("=== Basic List Operations ===\n")
# Creating a list
fruits = ['apple', 'banana', 'cherry']
print("Initial list:", fruits)
# Accessing elements by index
print("First element:", fruits[0])
print("Last element:", fruits[-1])
# Slicing lists
print("First two elements:", fruits[:2])
print("Elements from index 1 to end:", fruits[1:])
# Adding elements
fruits.append('date')
print("After append:", fruits)
fruits.insert(1, 'blueberry')
print("After insert at index 1:", fruits)
# Removing elements
fruits.remove('banana')
print("After removing 'banana':", fruits)
popped = fruits.pop(2)
print(f"After popping index 2 ({popped}):", fruits)
# Clearing the list
fruits.clear()
print("After clearing:", fruits)
print("\n")
def list_methods():
print("=== List Methods ===\n")
numbers = [4, 2, 9, 1]
print("Initial list:", numbers)
# Sorting
numbers.sort()
print("After sort:", numbers)
numbers.sort(reverse=True)
print("After sort descending:", numbers)
# Reversing
numbers.reverse()
print("After reverse:", numbers)
# Copying
numbers_copy = numbers.copy()
print("Copied list:", numbers_copy)
# Extending
numbers.extend([10, 11])
print("After extend:", numbers)
# Counting occurrences
count_10 = numbers.count(10)
print("Number of times 10 appears:", count_10)
# Finding index
index_of_9 = numbers.index(9)
print("Index of 9:", index_of_9)
print("\n")
def list_comprehensions():
print("=== List Comprehensions ===\n")
# Basic list comprehension
squares = [x**2 for x in range(10)]
print("Squares:", squares)
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print("Even Squares:", even_squares)
# Nested list comprehension
matrix = [[j for j in range(3)] for i in range(3)]
print("Matrix:", matrix)
# Flattening a nested list
flat = [item for sublist in matrix for item in sublist]
print("Flattened list:", flat)
print("\n")
def advanced_operations():
print("=== Advanced List Operations ===\n")
# Using map and lambda
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print("Doubled using map:", doubled)
# Using filter and lambda
even = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers using filter:", even)
# Using reduce
from functools import reduce
total = reduce(lambda x, y: x + y, numbers)
print("Sum using reduce:", total)
# List as a stack
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print("Stack after pushes:", stack)
print("Popped from stack:", stack.pop())
print("Stack after pop:", stack)
# List as a queue (using collections.deque is more efficient)
from collections import deque
queue = deque(['first', 'second', 'third'])
queue.append('fourth')
print("Queue after append:", list(queue))
print("Popped from queue:", queue.popleft())
print("Queue after popleft:", list(queue))
print("\n")
def nested_lists():
print("=== Nested Lists ===\n")
# Creating a nested list
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Matrix:")
for row in matrix:
print(row)
# Accessing nested elements
print("Element at row 2, column 3:", matrix[1][2])
# Modifying nested elements
matrix[0][0] = 10
print("After modifying matrix[0][0]:", matrix)
# List of lists vs list of tuples
list_of_lists = [[1, 2], [3, 4]]
list_of_tuples = [(1, 2), (3, 4)]
print("List of lists:", list_of_lists)
print("List of tuples:", list_of_tuples)
print("\n")
def list_slice_assignment():
print("=== List Slice Assignment ===\n")
letters = ['a', 'b', 'c', 'd', 'e']
print("Original list:", letters)
# Replacing a slice
letters[1:3] = ['x', 'y']
print("After slice assignment [1:3] = ['x', 'y']:", letters)
# Inserting multiple elements
letters[2:2] = ['m', 'n']
print("After inserting ['m', 'n'] at index 2:", letters)
# Deleting a slice
del letters[0:2]
print("After deleting first two elements:", letters)
print("\n")
def list_unpacking():
print("=== List Unpacking ===\n")
# Basic unpacking
numbers = [1, 2, 3]
a, b, c = numbers
print(f"Unpacked values: a={a}, b={b}, c={c}")
# Extended unpacking
numbers = [1, 2, 3, 4, 5]
a, *rest = numbers
print(f"Unpacked values: a={a}, rest={rest}")
*beginning, last = numbers
print(f"Unpacked values: beginning={beginning}, last={last}")
# Ignoring values
a, _, c = [1, 2, 3]
print(f"Unpacked with ignored value: a={a}, c={c}")
print("\n")
def list_generators():
print("=== List Generators and Generators Expressions ===\n")
# Generator expression
gen = (x**2 for x in range(5))
print("Generator expression:", gen)
print("Generated values:")
for val in gen:
print(val, end=' ')
print("\n")
# Using generators to save memory
def squares(n):
for x in range(n):
yield x ** 2
print("Using generator function:")
for square in squares(5):
print(square, end=' ')
print("\n")
print("\n")
def list_memory_management():
print("=== List Memory Management ===\n")
import sys
# Understanding list size
small_list = [1, 2, 3]
big_list = list(range(1000))
print(f"Size of small_list: {sys.getsizeof(small_list)} bytes")
print(f"Size of big_list: {sys.getsizeof(big_list)} bytes")
# Memory implications of list operations
import copy
original = [1, 2, 3]
shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)
print("Original:", original)
print("Shallow copy:", shallow_copy)
print("Deep copy:", deep_copy)
print("\n")
def list_compression():
print("=== Advanced List Compressions ===\n")
# Conditional list comprehensions
numbers = range(20)
divisible_by_3 = [x for x in numbers if x % 3 == 0]
print("Numbers divisible by 3:", divisible_by_3)
# Nested comprehensions
list1 = [1, 2]
list2 = ['a', 'b']
combinations = [(x, y) for x in list1 for y in list2]
print("Combinations of list1 and list2:", combinations)
# Dictionary and set comprehensions with lists
dict_comprehension = {x: x**2 for x in list1}
print("Dictionary comprehension:", dict_comprehension)
set_comprehension = {x for x in list2}
print("Set comprehension:", set_comprehension)
print("\n")
def main():
basic_operations()
list_methods()
list_comprehensions()
advanced_operations()
nested_lists()
list_slice_assignment()
list_unpacking()
list_generators()
list_memory_management()
list_compression()
print("=== All List Operations Demonstrated ===")
if __name__ == "__main__":
main()
Save the Script:
list_operations.py.Run the Script:
list_operations.py.python list_operations.py
Understand the Output:
Basic Operations (basic_operations):
List Methods (list_methods):
sort, reverse, copy, extend, count, and index.List Comprehensions (list_comprehensions):
Advanced Operations (advanced_operations):
map, filter, reduce, and treating lists as stacks and queues.Nested Lists (nested_lists):
List Slice Assignment (list_slice_assignment):
List Unpacking (list_unpacking):
List Generators (list_generators):
List Memory Management (list_memory_management):
Advanced List Compressions (list_compression):
Each section is designed to build upon the previous ones, providing a thorough understanding of list operations in Python. Feel free to experiment by modifying the examples or adding new ones to enhance your learning.
Not yet included in a published release.