├── LICENSE ├── README.md ├── CONTRIBUTING.md └── complexity_cheatsheet ├── tuples.md ├── dictionaries.md ├── strings.md ├── lists.md ├── sets.md └── complexity_overview.md /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Jaimin Bariya 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Complexity Cheat Sheet 📊 2 | 3 | A concise and comprehensive cheat sheet covering **time complexities** of Python's built-in data structures like Lists, Dictionaries, Sets, Tuples, and Strings. This resource is designed to help developers write **efficient** and **optimized** Python code. 4 | 5 | ## 🚀 Why Use This Cheat Sheet? 6 | - Understand the **average** and **worst-case complexities** of common operations. 7 | - Make informed decisions while working with Python's data structures. 8 | - Write optimized, faster programs with confidence. 9 | 10 | --- 11 | 12 | ## 🛠️ Cheat Sheets Available: 13 | - [Lists](complexity_cheatsheet/lists.md) 14 | - [Dictionaries](complexity_cheatsheet/dictionaries.md) 15 | - [Sets](complexity_cheatsheet/sets.md) 16 | - [Tuples](complexity_cheatsheet/tuples.md) 17 | - [Strings](complexity_cheatsheet/strings.md) 18 | - [Overview of Complexities](complexity_cheatsheet/complexity_overview.md) 19 | 20 | --- 21 | 22 | ## 📚 Highlights 23 | - **Lists**: Dynamic arrays with flexible operations. 24 | - **Dictionaries**: Hash-based key-value pairs for ultra-fast lookups. 25 | - **Sets**: Hash-based collections for unique items and efficient membership tests. 26 | - **Tuples**: Immutable, lightweight sequences. 27 | - **Strings**: Immutable text sequences optimized for searching and slicing. 28 | 29 | --- 30 | 31 | ## 📥 Contributions 32 | Want to help us make this cheat sheet even better? Check out our [CONTRIBUTING.md](CONTRIBUTING.md) file to get started! 33 | 34 | --- 35 | 36 | ## 📄 License 37 | This project is licensed under the [MIT License](LICENSE). 38 | 39 | --- 40 | 41 | ### 👀 Preview 42 | Here’s a quick look at time complexities for **Lists**: 43 | 44 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 45 | |----------------------|--------------------|-------------------|-------------------| 46 | | Append | `l.append(item)` | O(1) | O(1) (resize) | 47 | | Indexing | `l[i]` | O(1) | O(1) | 48 | | Containment | `item in l` | O(N) | O(N) | 49 | 50 | For more details, visit our dedicated cheat sheets! 🚀 51 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Python Data Structures Complexity Cheat Sheets 2 | 3 | We welcome contributions to improve and expand this repository! Whether you want to fix a typo, add examples, or propose new content, your help is appreciated. Follow the guidelines below to make the contribution process smooth and effective. 4 | 5 | --- 6 | 7 | ## 🛠 How to Contribute 8 | 9 | ### 1. Fork the Repository 10 | - Click on the **Fork** button at the top right of this repository. 11 | - This will create a copy of the repository under your GitHub account. 12 | 13 | ### 2. Clone Your Fork 14 | - Clone your forked repository to your local machine: 15 | ```bash 16 | git clone https://github.com//python-complexity-cheatsheets.git 17 | ``` 18 | 19 | ### 3. Create a Branch 20 | - Create a new branch to work on a specific feature or fix: 21 | ```bash 22 | git checkout -b feature/my-new-feature 23 | ``` 24 | 25 | ### 4. Make Your Changes 26 | - Edit or add files as needed. Ensure changes align with the repository’s structure and tone. 27 | - Follow Markdown best practices for readability and consistency. 28 | 29 | ### 5. Test Your Changes 30 | - Review your changes to ensure there are no errors in content or formatting. 31 | 32 | ### 6. Commit Your Changes 33 | - Commit your changes with a meaningful message: 34 | ```bash 35 | git add . 36 | git commit -m "Add explanation for tuple operations complexity" 37 | ``` 38 | 39 | ### 7. Push Your Branch 40 | - Push your changes to your forked repository: 41 | ```bash 42 | git push origin feature/my-new-feature 43 | ``` 44 | 45 | ### 8. Create a Pull Request 46 | - Open a Pull Request (PR) to the main repository: 47 | - Go to the **Pull Requests** tab in your fork. 48 | - Click on **New Pull Request**. 49 | - Write a clear description of the changes you made. 50 | 51 | --- 52 | 53 | ## 📝 Contribution Guidelines 54 | 55 | ### Content Guidelines 56 | 1. Ensure all complexities are correct and supported by references. 57 | 2. Provide concise, clear examples when adding new sections. 58 | 3. Use simple, beginner-friendly language. 59 | 60 | ### Formatting 61 | - Follow existing Markdown structure and tone. 62 | - Use tables for complexity information and highlight key terms with **bold** text. 63 | - Keep sentences short and readable. 64 | 65 | ### Code of Conduct 66 | Be respectful and constructive in your feedback and discussions. Refer to the [Code of Conduct](CODE_OF_CONDUCT.md) for more details. 67 | 68 | --- 69 | 70 | ## 💡 Ideas for Contributions 71 | Not sure where to start? Here are a few suggestions: 72 | 73 | 1. Fix typos or improve wording in existing files. 74 | 2. Add examples for complex operations. 75 | 3. Expand cheat sheets for additional data structures or libraries. 76 | 4. Create visual aids (like diagrams or flowcharts) to complement the content. 77 | 78 | --- 79 | 80 | Thank you for contributing! Together, we can make this resource more valuable for Python developers. 🚀 81 | -------------------------------------------------------------------------------- /complexity_cheatsheet/tuples.md: -------------------------------------------------------------------------------- 1 | # Tuples Time Complexity Cheat Sheet 2 | 3 | Python’s **tuple** is an immutable sequence type that is lightweight and ideal for fixed collections of items. This cheat sheet provides the average and worst-case time complexities for common tuple operations, helping developers write efficient Python code. 4 | 5 | --- 6 | 7 | ## 📋 Overview of Tuple Operations 8 | 9 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 10 | |-------------------------|--------------------------|-------------------|----------------| 11 | | Access by Index | `t[i]` | O(1) | O(1) | 12 | | Search | `x in t` | O(N) | O(N) | 13 | | Iteration | `for x in t:` | O(N) | O(N) | 14 | | Slicing | `t[start:end]` | O(k) | O(k) | 15 | | Concatenation | `t1 + t2` | O(len(t1) + len(t2)) | O(len(t1) + len(t2)) | 16 | | Length | `len(t)` | O(1) | O(1) | 17 | | Count | `t.count(x)` | O(N) | O(N) | 18 | | Index of Element | `t.index(x)` | O(N) | O(N) | 19 | 20 | --- 21 | 22 | ## 💡 Key Notes: 23 | 24 | 1. **Immutable Structure**: 25 | - Tuples are immutable, meaning their contents cannot be changed after creation. This makes them lightweight compared to lists. 26 | 27 | 2. **Fast Access**: 28 | - Accessing elements by index is O(1) since tuples are stored as contiguous memory blocks. 29 | 30 | 3. **Iteration and Search**: 31 | - Operations that involve scanning the tuple (like iteration or membership checks) have a time complexity of O(N), where N is the tuple's length. 32 | 33 | 4. **Slicing**: 34 | - Slicing creates a new tuple with a subset of elements. The time complexity is proportional to the size of the slice (k). 35 | 36 | --- 37 | 38 | ## 📖 Example Usage 39 | 40 | ```python 41 | # Example: Access and Search 42 | my_tuple = (10, 20, 30, 40, 50) 43 | element = my_tuple[2] # O(1) 44 | print(element) # Output: 30 45 | 46 | is_present = 20 in my_tuple # O(N) 47 | print(is_present) # Output: True 48 | 49 | # Example: Slicing 50 | sub_tuple = my_tuple[1:4] # O(k) 51 | print(sub_tuple) # Output: (20, 30, 40) 52 | 53 | # Example: Concatenation 54 | tuple1 = (1, 2) 55 | tuple2 = (3, 4) 56 | result = tuple1 + tuple2 # O(len(tuple1) + len(tuple2)) 57 | print(result) # Output: (1, 2, 3, 4) 58 | ``` 59 | 60 | --- 61 | 62 | ## 📥 When to Use Tuples? 63 | - Use tuples when you need **fixed, immutable collections** of items. 64 | - Ideal for use as **keys in dictionaries** or when working with **hash-based collections**. 65 | - Avoid tuples if the data is likely to change (use lists instead). 66 | 67 | --- 68 | 69 | Explore the [Complexity Overview](complexity_overview.md) for comparisons across all data structures! 70 | -------------------------------------------------------------------------------- /complexity_cheatsheet/dictionaries.md: -------------------------------------------------------------------------------- 1 | # Dictionaries Time Complexity Cheat Sheet 2 | 3 | Python’s **dictionary** is a hash table-based collection designed for fast key-value lookups. This cheat sheet provides the average and worst-case time complexities for common dictionary operations, helping developers optimize their Python code. 4 | 5 | --- 6 | 7 | ## 📋 Overview of Dictionary Operations 8 | 9 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 10 | |------------------------|-------------------------|-------------------|----------------| 11 | | Clear | `d.clear()` | O(1) | O(1) | 12 | | Construction | `dict(...)` | O(len(d)) | O(len(d)) | 13 | | Delete by Key | `del d[k]` | O(1) | O(N) | 14 | | Get Value by Key | `d.get(k)` | O(1) | O(N) | 15 | | Iteration (keys, vals, items) | `for k in d:` | O(N) | O(N) | 16 | | Length | `len(d)` | O(1) | O(1) | 17 | | Pop by Key | `d.pop(k)` | O(1) | O(N) | 18 | | Pop Item | `d.popitem()` | O(1) | O(1) | 19 | | Returning Views | `d.values()` | O(1) | O(1) | 20 | | Returning Keys | `d.keys()` | O(1) | O(1) | 21 | | Set Default | `d.setdefault(k, v)` | O(1) | O(N) | 22 | | Update | `d.update({...})` | O(len(update)) | O(len(update))| 23 | 24 | --- 25 | 26 | ## 💡 Key Notes: 27 | 28 | 1. **Hash-Based Structure**: 29 | - Dictionaries in Python are implemented as **hash tables**, enabling average O(1) complexity for key-based operations like `d[k]` or `d.get(k)`. 30 | 31 | 2. **Worst Case Scenarios**: 32 | - Rare collisions in hash functions or large deletions can lead to O(N) operations. 33 | 34 | 3. **Iteration**: 35 | - Iterating over keys, values, or items is O(N), where N is the size of the dictionary. 36 | 37 | 4. **Pop and Popitem**: 38 | - `d.pop(k)` removes a specific key and its value, while `d.popitem()` removes an arbitrary key-value pair (LIFO order). 39 | 40 | --- 41 | 42 | ## 📖 Example Usage 43 | 44 | ```python 45 | # Example: Adding and Retrieving Values 46 | my_dict = {"a": 1, "b": 2, "c": 3} 47 | my_dict["d"] = 4 # O(1) 48 | value = my_dict["a"] # O(1) 49 | 50 | # Example: Iteration 51 | for key, value in my_dict.items(): # O(N) 52 | print(f"{key}: {value}") 53 | 54 | # Example: Pop Operations 55 | popped_value = my_dict.pop("b") # O(1) 56 | print(my_dict) # Output: {"a": 1, "c": 3, "d": 4} 57 | ``` 58 | 59 | --- 60 | 61 | ## 📥 When to Use Dictionaries? 62 | - Use dictionaries for **fast lookups**, **insertion**, and **deletion** by key. 63 | - Avoid using dictionaries if order is critical (consider `OrderedDict` or Python 3.7+ where `dict` maintains insertion order). 64 | 65 | --- 66 | 67 | Explore the [Complexity Overview](complexity_overview.md) for comparisons across all data structures! 68 | -------------------------------------------------------------------------------- /complexity_cheatsheet/strings.md: -------------------------------------------------------------------------------- 1 | # Strings Time Complexity Cheat Sheet 2 | 3 | Python’s **string** is an immutable sequence of characters, optimized for text processing. This cheat sheet provides the average and worst-case time complexities for common string operations, helping developers write efficient Python code. 4 | 5 | --- 6 | 7 | ## 📋 Overview of String Operations 8 | 9 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 10 | |-------------------------|--------------------------|-------------------|----------------| 11 | | Access by Index | `s[i]` | O(1) | O(1) | 12 | | Search | `x in s` | O(N) | O(N) | 13 | | Iteration | `for c in s:` | O(N) | O(N) | 14 | | Slicing | `s[start:end]` | O(k) | O(k) | 15 | | Concatenation | `s1 + s2` | O(len(s1) + len(s2)) | O(len(s1) + len(s2)) | 16 | | Length | `len(s)` | O(1) | O(1) | 17 | | Count | `s.count(x)` | O(N) | O(N) | 18 | | Find/Index | `s.find(x)`, `s.index(x)`| O(N) | O(N) | 19 | | Replace | `s.replace(a, b)` | O(N) | O(N) | 20 | | Split | `s.split(delimiter)` | O(N) | O(N) | 21 | | Join | `'delimiter'.join(list)`| O(N) | O(N) | 22 | 23 | --- 24 | 25 | ## 💡 Key Notes: 26 | 27 | 1. **Immutable Nature**: 28 | - Strings in Python are immutable, so any operation that modifies a string results in the creation of a new string. 29 | 30 | 2. **Access and Iteration**: 31 | - Accessing characters by index and iterating through a string is efficient with O(1) and O(N) complexities respectively. 32 | 33 | 3. **Concatenation and Join**: 34 | - Concatenating strings using `+` is O(N), as it creates a new string. Use `'delimiter'.join(list)` for efficient concatenation of multiple strings. 35 | 36 | 4. **Search and Replace**: 37 | - Operations like `find`, `index`, `replace`, and `split` scan the entire string, resulting in O(N) complexity. 38 | 39 | --- 40 | 41 | ## 📖 Example Usage 42 | 43 | ```python 44 | # Example: Access and Search 45 | my_string = "hello world" 46 | element = my_string[4] # O(1) 47 | print(element) # Output: o 48 | 49 | is_present = "world" in my_string # O(N) 50 | print(is_present) # Output: True 51 | 52 | # Example: Slicing and Concatenation 53 | sub_string = my_string[0:5] # O(k) 54 | print(sub_string) # Output: hello 55 | 56 | concat_string = my_string + "!" # O(len(my_string) + len("!")) 57 | print(concat_string) # Output: hello world! 58 | 59 | # Example: Join and Split 60 | words = my_string.split() # O(N) 61 | print(words) # Output: ['hello', 'world'] 62 | 63 | joined_string = " ".join(words) # O(N) 64 | print(joined_string) # Output: hello world 65 | ``` 66 | 67 | --- 68 | 69 | ## 📥 When to Use Strings? 70 | - Use strings for **text manipulation** and **character sequences**. 71 | - Opt for `bytearray` when working with **mutable sequences** of bytes for better performance. 72 | 73 | --- 74 | 75 | Explore the [Complexity Overview](complexity_overview.md) for comparisons across all data structures! 76 | -------------------------------------------------------------------------------- /complexity_cheatsheet/lists.md: -------------------------------------------------------------------------------- 1 | # Lists Time Complexity Cheat Sheet 2 | 3 | Python’s **list** is a versatile, ordered, and mutable sequence. This cheat sheet provides the average and worst-case time complexities for common list operations, helping developers write optimized and efficient Python code. 4 | 5 | --- 6 | 7 | ## 📋 Overview of List Operations 8 | 9 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 10 | |----------------------|----------------------|-------------------|-------------------| 11 | | Append | `l.append(item)` | O(1) | O(1) (resize) | 12 | | Clear | `l.clear()` | O(1) | O(1) | 13 | | Containment | `item in l` | O(N) | O(N) | 14 | | Copy | `l.copy()` | O(N) | O(N) | 15 | | Delete by Index | `del l[i]` | O(N) | O(N) | 16 | | Extend | `l.extend(another)` | O(N) | O(N) | 17 | | Equality Check | `l1 == l2` | O(N) | O(N) | 18 | | Indexing | `l[i]` | O(1) | O(1) | 19 | | Iteration | `for item in l:` | O(N) | O(N) | 20 | | Length | `len(l)` | O(1) | O(1) | 21 | | Multiplication | `k * l` | O(k * N) | O(k * N) | 22 | | Min/Max | `min(l), max(l)` | O(N) | O(N) | 23 | | Pop from End | `l.pop(-1)` | O(1) | O(1) | 24 | | Pop Intermediate | `l.pop(i)` | O(N) | O(N) | 25 | | Remove | `l.remove(x)` | O(N) | O(N) | 26 | | Reverse | `l.reverse()` | O(N) | O(N) | 27 | | Slicing | `l[x:y]` | O(y - x) | O(y - x) | 28 | | Sort | `l.sort()` | O(N log N) | O(N log N) | 29 | | Store by Index | `l[i] = x` | O(1) | O(1) | 30 | 31 | --- 32 | 33 | ## 💡 Key Notes: 34 | 35 | 1. **Dynamic Resizing**: 36 | - Lists are implemented as dynamic arrays in Python. When a list exceeds its allocated memory, it resizes by allocating more memory, leading to an **amortized O(1)** complexity for append operations. 37 | 38 | 2. **Indexing and Slicing**: 39 | - Accessing or slicing a list uses **direct indexing**, making operations like `l[i]` O(1) and slicing `l[x:y]` proportional to the slice length (O(y-x)). 40 | 41 | 3. **Sorting**: 42 | - Python’s `list.sort()` uses the Timsort algorithm, which has a complexity of **O(N log N)** in the average and worst cases. 43 | 44 | 4. **Common Pitfall**: 45 | - Using operations like `x in l` for containment checks on large lists can be inefficient (O(N)). Consider using sets for such scenarios (O(1) containment). 46 | 47 | --- 48 | 49 | ## 📖 Example Usage 50 | 51 | ```python 52 | # Example: Append and Sort 53 | my_list = [3, 1, 4, 1] 54 | my_list.append(5) # O(1) 55 | my_list.sort() # O(N log N) 56 | print(my_list) # Output: [1, 1, 3, 4, 5] 57 | 58 | # Example: Slicing 59 | sub_list = my_list[1:3] # O(2), as slice length is 2 60 | print(sub_list) # Output: [1, 3] 61 | ``` 62 | 63 | --- 64 | 65 | ## 📥 When to Use Lists? 66 | - Use lists when you need **ordered**, **mutable** sequences with frequent appends, indexing, or slicing. 67 | - For **faster membership checks** or **unique elements**, consider using **sets**. 68 | 69 | --- 70 | 71 | Explore the [Complexity Overview](complexity_overview.md) for comparisons across all data structures! 72 | -------------------------------------------------------------------------------- /complexity_cheatsheet/sets.md: -------------------------------------------------------------------------------- 1 | # Sets Time Complexity Cheat Sheet 2 | 3 | Python’s **set** is a hash-based collection optimized for fast membership tests and set operations. This cheat sheet provides the average and worst-case time complexities for common set operations, helping developers write efficient Python code. 4 | 5 | --- 6 | 7 | ## 📋 Overview of Set Operations 8 | 9 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 10 | |-------------------------|--------------------------|---------------------------|-------------------------| 11 | | Add | `s.add(item)` | O(1) | O(N) | 12 | | Clear | `s.clear()` | O(1) | O(1) | 13 | | Copy | `s.copy()` | O(N) | O(N) | 14 | | Containment | `item in s` | O(1) | O(N) | 15 | | Creation | `set(iterable)` | O(len(iterable)) | O(len(iterable)) | 16 | | Discard | `s.discard(item)` | O(1) | O(N) | 17 | | Difference | `s1 - s2` | O(len(s1)) | O(len(s1)) | 18 | | Difference Update | `s1.difference_update(s2)` | O(len(s2)) | - | 19 | | Equality Check | `s1 == s2` | O(min(len(s1), len(s2))) | O(min(len(s1), len(s2)))| 20 | | Intersection | `s1 & s2` | O(min(len(s1), len(s2))) | O(min(len(s1), len(s2)))| 21 | | Iteration | `for item in s:` | O(N) | O(N) | 22 | | Is Subset | `s1 <= s2` | O(len(s1)) | O(len(s1)) | 23 | | Is Superset | `s1 >= s2` | O(len(s2)) | O(len(s2)) | 24 | | Pop | `s.pop()` | O(1) | O(N) | 25 | | Union | `s1 | s2` | O(len(s1) + len(s2)) | - | 26 | | Symmetric Difference | `s1 ^ s2` | O(len(s1)) | O(len(s1) * len(s2)) | 27 | 28 | --- 29 | 30 | ## 💡 Key Notes: 31 | 32 | 1. **Hash-Based Structure**: 33 | - Sets in Python use a hash table, enabling O(1) average complexity for operations like `add`, `discard`, and membership tests (`item in s`). 34 | 35 | 2. **Worst Case Scenarios**: 36 | - Hash collisions or resizing during operations can degrade performance to O(N). 37 | 38 | 3. **Set Operations**: 39 | - Operations like union (`|`), intersection (`&`), and difference (`-`) depend on the sizes of the sets involved. 40 | 41 | 4. **Pop Behavior**: 42 | - The `pop()` method removes and returns an arbitrary element from the set. If the set is empty, it raises a `KeyError`. 43 | 44 | --- 45 | 46 | ## 📖 Example Usage 47 | 48 | ```python 49 | # Example: Add and Membership Test 50 | my_set = {1, 2, 3} 51 | my_set.add(4) # O(1) 52 | print(4 in my_set) # True (O(1)) 53 | 54 | # Example: Union and Intersection 55 | set1 = {1, 2, 3} 56 | set2 = {3, 4, 5} 57 | union_set = set1 | set2 # O(len(set1) + len(set2)) 58 | print(union_set) # Output: {1, 2, 3, 4, 5} 59 | 60 | intersection_set = set1 & set2 # O(min(len(set1), len(set2))) 61 | print(intersection_set) # Output: {3} 62 | ``` 63 | 64 | --- 65 | 66 | ## 📥 When to Use Sets? 67 | - Use sets for **fast membership checks**, **removing duplicates**, and performing **set operations** like union, intersection, and difference. 68 | - Avoid sets when **order** or **duplicate values** are required (use lists or dictionaries instead). 69 | 70 | --- 71 | 72 | Explore the [Complexity Overview](complexity_overview.md) for comparisons across all data structures! 73 | -------------------------------------------------------------------------------- /complexity_cheatsheet/complexity_overview.md: -------------------------------------------------------------------------------- 1 | # Complexity Overview of Python Data Structures 2 | 3 | This overview summarizes the average and worst-case time complexities for common operations across Python's built-in data structures, including **lists**, **dictionaries**, **sets**, **tuples**, and **strings**. Use this cheat sheet to write efficient and optimized Python code. 4 | 5 | --- 6 | 7 | ## 📋 Data Structures and Their Operations 8 | 9 | ### Lists 10 | Python's **list** is an ordered, mutable sequence, often implemented as a dynamic array. 11 | 12 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 13 | |-------------------------|------------------------|-------------------|-----------------| 14 | | Append | `l.append(x)` | O(1) | O(1)* | 15 | | Access by Index | `l[i]` | O(1) | O(1) | 16 | | Search | `x in l` | O(N) | O(N) | 17 | | Delete by Index | `del l[i]` | O(N) | O(N) | 18 | | Slice | `l[start:end]` | O(k) | O(k) | 19 | | Sort | `l.sort()` | O(N log N) | O(N log N) | 20 | 21 | [Learn more about lists here](lists.md). 22 | 23 | --- 24 | 25 | ### Dictionaries 26 | Python's **dict** is implemented as a hash table, making it highly efficient for key-based operations. 27 | 28 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 29 | |-------------------------|------------------------|-------------------|-----------------| 30 | | Access by Key | `d[k]` | O(1) | O(N) | 31 | | Insert/Update | `d[k] = v` | O(1) | O(N) | 32 | | Delete by Key | `del d[k]` | O(1) | O(N) | 33 | | Iteration (Keys/Values)| `for k in d:` | O(N) | O(N) | 34 | 35 | [Learn more about dictionaries here](dictionaries.md). 36 | 37 | --- 38 | 39 | ### Sets 40 | Python's **set** is a hash-based collection optimized for membership tests and set operations. 41 | 42 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 43 | |-------------------------|------------------------|-------------------|-----------------| 44 | | Add Element | `s.add(x)` | O(1) | O(N) | 45 | | Membership Test | `x in s` | O(1) | O(N) | 46 | | Remove Element | `s.remove(x)` | O(1) | O(N) | 47 | | Union | `s1 | s2` | O(len(s1) + len(s2)) | O(len(s1) + len(s2)) | 48 | | Intersection | `s1 & s2` | O(min(len(s1), len(s2))) | O(min(len(s1), len(s2))) | 49 | 50 | [Learn more about sets here](sets.md). 51 | 52 | --- 53 | 54 | ### Tuples 55 | Python's **tuple** is an immutable sequence, making it lighter than lists but with fewer operations. 56 | 57 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 58 | |-------------------------|------------------------|-------------------|-----------------| 59 | | Access by Index | `t[i]` | O(1) | O(1) | 60 | | Search | `x in t` | O(N) | O(N) | 61 | | Slice | `t[start:end]` | O(k) | O(k) | 62 | 63 | [Learn more about tuples here](tuples.md). 64 | 65 | --- 66 | 67 | ### Strings 68 | Python's **string** is an immutable sequence of characters, optimized for text processing. 69 | 70 | | **Operation** | **Examples** | **Average Case** | **Worst Case** | 71 | |-------------------------|------------------------|-------------------|-----------------| 72 | | Access by Index | `s[i]` | O(1) | O(1) | 73 | | Concatenation | `s1 + s2` | O(len(s1) + len(s2)) | O(len(s1) + len(s2)) | 74 | | Search | `x in s` | O(N) | O(N) | 75 | | Slice | `s[start:end]` | O(k) | O(k) | 76 | | Split | `s.split()` | O(N) | O(N) | 77 | 78 | [Learn more about strings here](strings.md). 79 | 80 | --- 81 | 82 | ## 🧠 Tips for Writing Efficient Code 83 | 84 | 1. **Choose the right data structure**: 85 | - Use **lists** for ordered, mutable sequences. 86 | - Use **dictionaries** or **sets** for fast lookups. 87 | - Use **tuples** or **strings** for immutable data. 88 | 89 | 2. **Avoid unnecessary operations**: 90 | - Minimize concatenation in loops (use `.join()` for strings). 91 | - Use slicing and comprehensions where possible. 92 | 93 | 3. **Profile your code**: 94 | - Use tools like `timeit` and `cProfile` to identify bottlenecks. 95 | 96 | --- 97 | 98 | Optimize your Python code with this cheat sheet! 🎉 99 | --------------------------------------------------------------------------------