Python Lists & NumPy Arrays
Physics simulations handle collections like particle positions or time series. Python provides lists while NumPy provides arrays.
Python lists are ordered, mutable, and can hold mixed types. They use 0-indexing: temperatures[0] gets the first item, and len() gives the count.
NumPy arrays are homogeneous, fast, and support vectorised operations. Functions like np.linspace generate points, and operations apply element-wise.
| Feature | Python Lists | NumPy Arrays |
|---|---|---|
| Types | Mixed / Heterogeneous | Homogeneous |
| Speed | Interpreted Python | Compiled C |
| Memory | Object overhead | Raw compact data |
Tip: Usenp.arrayfor numerical computation and Pythonlistfor heterogeneous or small collections.
Slicing, Speed & Pitfalls
Slicing extracts subsets using start:stop:step syntax. For example, data[1:4] returns indices 1, 2, and 3, while data[::2] takes every second element.
Broadcasting allows math operations like a * 2 to multiply every element without writing an explicit loop.
| Operation | Syntax Example | Result |
|---|---|---|
| Basic Slice | data[1:4] | [20, 30, 40] |
| Strided Slice | data[::2] | [10, 30, 50] |
Common pitfall: Assigning a list copies a reference, not the data. Afterb = a, mutatingbmutatesatoo. Always use explicit copies likelist(a)or slicing to fork data.