-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtuples.py
More file actions
366 lines (284 loc) · 10.3 KB
/
Copy pathtuples.py
File metadata and controls
366 lines (284 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"""
Module: tuples.py
Topic: Tuples in Python
Level: Beginner
This file teaches you about:
- Tuple creation and basics
- Tuple indexing and slicing
- Tuple methods
- Tuple unpacking
- Named tuples
- When to use tuples vs lists
"""
# =============================================================================
# SECTION 1: TUPLE CREATION
# =============================================================================
print("=" * 60)
print("TUPLE CREATION")
print("=" * 60)
# Different ways to create tuples
tuple1 = (1, 2, 3, 4, 5) # With parentheses
tuple2 = 1, 2, 3, 4, 5 # Without parentheses (tuple packing)
tuple3 = tuple(range(5)) # Using tuple() constructor
tuple4 = () # Empty tuple
tuple5 = tuple() # Empty tuple (constructor)
tuple6 = (42,) # Single element tuple (comma required!)
print(f"With parentheses: {tuple1}")
print(f"Without parentheses: {tuple2}")
print(f"tuple(range(5)): {tuple3}")
print(f"Empty tuple (): {tuple4}")
print(f"Single element (42,): {tuple6}") # Note the comma!
# Common mistake: single element without comma
not_a_tuple = (42) # This is just an integer!
print(f"\nWithout comma (42): {not_a_tuple}, type: {type(not_a_tuple)}")
print(f"With comma (42,): {tuple6}, type: {type(tuple6)}")
# =============================================================================
# SECTION 2: TUPLE CHARACTERISTICS
# =============================================================================
print("\n" + "=" * 60)
print("TUPLE CHARACTERISTICS")
print("=" * 60)
# Tuples are immutable
coordinates = (10, 20)
print(f"Tuple: {coordinates}")
try:
coordinates[0] = 15 # This raises TypeError
except TypeError as e:
print(f"Attempting to modify tuple raises: {type(e).__name__}")
# But tuples can contain mutable objects
mixed = (1, [2, 3], 4)
print(f"\nTuple with mutable list: {mixed}")
mixed[1].append(5) # This works!
print(f"After appending to inner list: {mixed}")
# Tuple with different types
person = ("Alice", 25, "Engineer", True)
print(f"\nMixed types: {person}")
# Nested tuples
nested = ((1, 2), (3, 4), (5, 6))
print(f"Nested tuple: {nested}")
# =============================================================================
# SECTION 3: TUPLE INDEXING AND SLICING
# =============================================================================
print("\n" + "=" * 60)
print("TUPLE INDEXING AND SLICING")
print("=" * 60)
fruits = ('apple', 'banana', 'cherry', 'date', 'elderberry')
print(f"Tuple: {fruits}")
print(f"\nIndexing:")
print(f" fruits[0]: {fruits[0]}")
print(f" fruits[-1]: {fruits[-1]}")
print(f" fruits[2]: {fruits[2]}")
print(f"\nSlicing:")
print(f" fruits[1:3]: {fruits[1:3]}")
print(f" fruits[:3]: {fruits[:3]}")
print(f" fruits[2:]: {fruits[2:]}")
print(f" fruits[::-1]: {fruits[::-1]}")
# Nested tuple indexing
matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
print(f"\nNested indexing:")
print(f" matrix[0]: {matrix[0]}")
print(f" matrix[0][1]: {matrix[0][1]}")
# =============================================================================
# SECTION 4: TUPLE UNPACKING
# =============================================================================
print("\n" + "=" * 60)
print("TUPLE UNPACKING")
print("=" * 60)
# Basic unpacking
point = (10, 20)
x, y = point
print(f"Basic unpacking: x={x}, y={y}")
# Unpacking with multiple variables
person = ("Alice", 25, "Engineer")
name, age, job = person
print(f"Multiple unpacking: name={name}, age={age}, job={job}")
# Extended unpacking with *
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(f"\nExtended unpacking:")
print(f" first={first}, middle={middle}, last={last}")
first, *rest = numbers
print(f" first={first}, rest={rest}")
*beginning, last = numbers
print(f" beginning={beginning}, last={last}")
# Swapping variables
a, b = 10, 20
print(f"\nBefore swap: a={a}, b={b}")
a, b = b, a
print(f"After swap: a={a}, b={b}")
# Unpacking in loops
print("\nUnpacking in loops:")
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
for num, letter in pairs:
print(f" {num} -> {letter}")
# =============================================================================
# SECTION 5: TUPLE METHODS
# =============================================================================
print("\n" + "=" * 60)
print("TUPLE METHODS")
print("=" * 60)
# Tuples have only two methods: count() and index()
numbers = (1, 2, 3, 2, 4, 2, 5)
print(f"Tuple: {numbers}")
print(f" count(2): {numbers.count(2)}")
print(f" index(3): {numbers.index(3)}")
print(f" index(2, 2): {numbers.index(2, 2)}") # Start from index 2
# =============================================================================
# SECTION 6: TUPLE OPERATIONS
# =============================================================================
print("\n" + "=" * 60)
print("TUPLE OPERATIONS")
print("=" * 60)
# Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
print(f"Concatenation: {tuple1 + tuple2}")
# Repetition
print(f"Repetition: {tuple1 * 3}")
# Membership
print(f"\nMembership:")
print(f" 2 in {tuple1}: {2 in tuple1}")
print(f" 5 in {tuple1}: {5 in tuple1}")
# Length, Min, Max, Sum
numbers = (3, 1, 4, 1, 5, 9)
print(f"\nTuple: {numbers}")
print(f" len(): {len(numbers)}")
print(f" min(): {min(numbers)}")
print(f" max(): {max(numbers)}")
print(f" sum(): {sum(numbers)}")
# Comparison (lexicographic)
print(f"\nComparison:")
print(f" (1, 2, 3) < (1, 2, 4): {(1, 2, 3) < (1, 2, 4)}")
print(f" (1, 2) < (1, 2, 3): {(1, 2) < (1, 2, 3)}")
# =============================================================================
# SECTION 7: TUPLES AS DICTIONARY KEYS
# =============================================================================
print("\n" + "=" * 60)
print("TUPLES AS DICTIONARY KEYS")
print("=" * 60)
# Tuples can be dictionary keys (lists cannot!)
locations = {
(40.7128, -74.0060): "New York",
(51.5074, -0.1278): "London",
(35.6762, 139.6503): "Tokyo"
}
print("Using tuples as dictionary keys:")
for coords, city in locations.items():
print(f" {coords}: {city}")
# Look up by coordinates
ny_coords = (40.7128, -74.0060)
print(f"\nLookup {ny_coords}: {locations[ny_coords]}")
# Lists cannot be dictionary keys
try:
bad_dict = {[1, 2]: "value"}
except TypeError as e:
print(f"\nUsing list as key raises: {type(e).__name__}")
# =============================================================================
# SECTION 8: NAMED TUPLES
# =============================================================================
print("\n" + "=" * 60)
print("NAMED TUPLES")
print("=" * 60)
from collections import namedtuple
# Create a named tuple class
Point = namedtuple('Point', ['x', 'y'])
Person = namedtuple('Person', 'name age job')
# Create instances
p = Point(10, 20)
alice = Person("Alice", 25, "Engineer")
print(f"Point: {p}")
print(f"Person: {alice}")
# Access by name or index
print(f"\nAccess by name: p.x = {p.x}, p.y = {p.y}")
print(f"Access by index: p[0] = {p[0]}, p[1] = {p[1]}")
# Named tuple methods
print(f"\nNamed tuple methods:")
print(f" _fields: {alice._fields}")
print(f" _asdict(): {alice._asdict()}")
# Create from iterable
coords = [30, 40]
p2 = Point._make(coords)
print(f" _make([30, 40]): {p2}")
# =============================================================================
# SECTION 9: TUPLES VS LISTS
# =============================================================================
print("\n" + "=" * 60)
print("TUPLES VS LISTS")
print("=" * 60)
import sys
# Memory usage
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3, 4, 5)
print("Memory usage comparison:")
print(f" List size: {sys.getsizeof(list_data)} bytes")
print(f" Tuple size: {sys.getsizeof(tuple_data)} bytes")
# Performance comparison
import timeit
print("\nCreation time (100000 iterations):")
list_time = timeit.timeit('[1, 2, 3, 4, 5]', number=100000)
tuple_time = timeit.timeit('(1, 2, 3, 4, 5)', number=100000)
print(f" List: {list_time:.4f} seconds")
print(f" Tuple: {tuple_time:.4f} seconds")
print("\nWhen to use TUPLES:")
print(" ✓ Data that shouldn't change (coordinates, constants)")
print(" ✓ Dictionary keys")
print(" ✓ Return multiple values from functions")
print(" ✓ Heterogeneous data (like a record)")
print("\nWhen to use LISTS:")
print(" ✓ Data that needs to be modified")
print(" ✓ Need to add/remove elements")
print(" ✓ Homogeneous data (like a collection)")
print(" ✓ Need sorting, reversing, etc.")
# =============================================================================
# SECTION 10: PRACTICAL EXAMPLES
# =============================================================================
print("\n" + "=" * 60)
print("PRACTICAL EXAMPLES")
print("=" * 60)
def get_statistics(numbers):
"""Return multiple statistics as a tuple."""
if not numbers:
return (None, None, None, None)
minimum = min(numbers)
maximum = max(numbers)
total = sum(numbers)
average = total / len(numbers)
return (minimum, maximum, total, average)
print("\nReturning multiple values:")
data = [10, 20, 30, 40, 50]
stats = get_statistics(data)
print(f" Data: {data}")
print(f" Statistics: min={stats[0]}, max={stats[1]}, sum={stats[2]}, avg={stats[3]:.1f}")
# Unpack returned tuple
minimum, maximum, total, average = get_statistics(data)
print(f" Unpacked: min={minimum}, max={maximum}")
def find_min_max(iterable):
"""Find minimum and maximum in a single pass."""
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return (None, None)
minimum = maximum = first
for value in iterator:
if value < minimum:
minimum = value
if value > maximum:
maximum = value
return (minimum, maximum)
print(f"\nSingle pass min/max:")
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
min_val, max_val = find_min_max(numbers)
print(f" Numbers: {numbers}")
print(f" Min: {min_val}, Max: {max_val}")
# Using tuples for safe data
DAYS_OF_WEEK = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
print(f"\nConstants (immutable): {DAYS_OF_WEEK}")
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
print("\n" + "=" * 60)
print("✅ You've learned about Python tuples!")
print("📚 Next: Learn about dictionaries in dictionaries.py")
print("=" * 60)