Python Dict | ||||||||||||||||||||||||||||||
Python Data Structures with Dict List Set and TupleExplain the lists, sets, dictionaries and tuples built-in collections with definition and practical examples.
| ||||||||||||||||||||||||||||||
Python Data Structures with Dict, List, Set and TuplePython main data structures are lists, sets, tuples, and dictionaries. Learn how to use the of Python’s built-in collections with examples. Python collection are used to store and organize data with different schemas. Summary of Key Features Python Collections: Lists : are ordered, mutable and allows duplicates Dictionaries : are ordered and mutable key–value pairs with unique keys. Tuples : are ordered, immutable and allows duplicates. Sets : are unordered, immutable and duplicates are NOT allowed. 📘 There are four collection data types in the Python programming language.
Why data structures are important?
| ||||||||||||||||||||||||||||||
ListList is a mutable ordered collection [] Syntax: my_list = [1, 2, 3] Definition of Lists: The List is an ordered, mutable collection of items. - Key Features of List: - Allows duplicates. - Elements can be changed, added, or removed. - Supports indexing and slicing. - Examples and use cases: When you need a dynamic sequence of items, like a shopping cart. | ||||||||||||||||||||||||||||||
DictDictionary (Dict) is a store key–value pairs for fast lookups. Definition of Dictionary: The Dict is a collection of key–value pairs. {} Syntax: my_dict = {"name": "Alice", "age": 25} Key Features of Dictionaries: - Keys must be unique and immutable (like strings, numbers, tuples). - Values can be any type and are mutable. - Provides fast lookups by key. - Examples and use cases: When you need to map relationships, like storing user profiles. | ||||||||||||||||||||||||||||||
TupleTuple is an immutable ordered collection Definition of Tuples: The Tuple is an ordered, immutable collection of items. Syntax: my_tuple = (1, 2, 3) Key Features of Tuples: - Cannot be modified after creation. - Allows duplicates. - Supports indexing and slicing. Examples and use cases: When you want fixed data that should not change, like geographic coordinates (lat, long). | ||||||||||||||||||||||||||||||
Collections Comparison🔍 Comparison Table of Data Structures in Python
✅ Compare key features of collections in python:
| ||||||||||||||||||||||||||||||
Key Takeaways⚡ Practical Examples Main key uses of different data collections in python: - Use lists when you need flexible, changeable sequences. - Use tuples when you want fixed, unchangeable data. - Use dictionaries when you need fast lookups or mappings between keys and values. | ||||||||||||||||||||||||||||||
List Example
# Use a list if you want rows with ordered and duplicates allowed: table_rows = [] table_rows.append(['1', '2']) table_rows.append(['3', '4']) print(table_rows) # Output: [['1', '2'], ['3', '4']] # Example : table_rows.append(('1','2')) # ✅ tuple inside list | ||||||||||||||||||||||||||||||
Tuple Example
| ||||||||||||||||||||||||||||||
Dictionary Example
# Use a dictionary if you need key-value pairs: table_rows = {} table_rows['row1'] = ['1', '2'] print(table_rows) # Output: {'row1': ['1', '2']} row_item = {'uid': '123', 'name': 'Alice'} print(f"Item id {row_item['uid']}") # Output: Item id 123 | ||||||||||||||||||||||||||||||
Sets | ||||||||||||||||||||||||||||||
ok create small "table-like" structure in Python that behaves more like a spreadsheet ------------ by looking at sets. 🔹 Python Set Definition A set is an unordered collection of unique elements. It’s mutable, but it doesn’t allow duplicates. Syntax my_set = {1, 2, 3} empty_set = set() # {} creates an empty dict, not a set | ||||||||||||||||||||||||||||||
Key Features - Unordered → No guaranteed order of elements. - Unique elements → Automatically removes duplicates. - Mutable → You can add or remove items. - Efficient operations → Optimized for membership tests and mathematical set operations. Common Operations # Create a set numbers = {1, 2, 3, 3, 4} print(numbers) # {1, 2, 3, 4} (duplicates removed) # Add and remove numbers.add(5) numbers.remove(2) # Membership test print(3 in numbers) # True # Set operations a = {1, 2, 3} b = {3, 4, 5} print(a.union(b)) # {1, 2, 3, 4, 5} print(a.intersection(b)) # {3} print(a.difference(b)) # {1, 2} Use Cases - Removing duplicates from a list. - Fast membership checks (x in set is faster than x in list). - Performing mathematical set operations (union, intersection, difference). - Representing collections where order doesn’t matter, like tags or categories. | ||||||||||||||||||||||||||||||
👉 So, if you want unique, unordered data with fast membership checks, sets are the way to go. -------- Would you like me to also explain frozensets (the immutable version of sets), since they’re often overlooked but useful in certain cases? Perfect, let’s dive into frozensets — the lesser-known sibling of sets in Python. ❄️ Frozenset Definition A frozenset is an immutable set. It works just like a regular set, but once created, you cannot add or remove elements. Syntax # Creating a frozenset fs = frozenset([1, 2, 3, 3]) print(fs) # frozenset({1, 2, 3}) Key Features - Immutable → Cannot be changed after creation. - Unordered → Like sets, no guaranteed order. - Unique elements → Duplicates are automatically removed. - Hashable → Unlike normal sets, frozensets can be used as dictionary keys or stored inside other sets. Common Operations # Frozenset creation a = frozenset([1, 2, 3]) b = frozenset([3, 4, 5]) # Set operations still work print(a.union(b)) # frozenset({1, 2, 3, 4, 5}) print(a.intersection(b)) # frozenset({3}) print(a.difference(b)) # frozenset({1, 2}) # ❌ Cannot modify # a.add(6) # Error: frozenset object has no attribute 'add' Use Cases - When you need a set that must not change, ensuring data integrity. - As dictionary keys or elements inside other sets (since they’re hashable). - Useful in functional programming or when working with constants.
| ||||||||||||||||||||||||||||||
👉 Think of frozenset as a “read-only set.” If you want the benefits of set operations but need to guarantee that the collection won’t change, frozenset is the right choice. Would you like me to show you a real-world example where frozensets are particularly useful, like using them as dictionary keys for caching results? -- Here’s a real-world example of how frozenset can be useful — specifically when you want to use sets as dictionary keys for caching or mapping results. 🧩 Example: Using Frozenset as Dictionary Keys Imagine you’re writing a function that calculates something based on a group of items. You want to cache results so you don’t recompute the same thing twice. Since normal sets are not hashable, you can’t use them as dictionary keys — but frozensets solve this. # Example: caching results of a function cache = {} def expensive_operation(items): # Convert to frozenset so it can be used as a key key = frozenset(items) if key in cache: print("Fetching from cache...") return cache[key] # Simulate expensive computation result = sum(items) * 2 cache[key] = result print("Computed and cached...") return result # Usage print(expensive_operation([1, 2, 3])) # Computed and cached... print(expensive_operation([3, 2, 1])) # Fetching from cache... 🔍 What’s Happening Here - frozenset([1, 2, 3]) and frozenset([3, 2, 1]) are considered the same key because sets ignore order. - The first call computes and stores the result. - The second call retrieves it instantly from the cache. ✅ Why Frozenset Works Well - Hashable → Can be used as dictionary keys. - Immutable → Guarantees the key won’t change after insertion. - Order-independent → Perfect for grouping items where order doesn’t matter. 👉 This pattern is common in memoization, caching, and graph algorithms where you need to store results for combinations of items. Would you like me to also show you a graph-related example (like storing visited edges with frozensets) to see how it’s applied in algorithms? ------------------- | ||||||||||||||||||||||||||||||
Python LISTS Note: Python does not have built-in support for Arrays, but Python Lists can be used instead. mylist = ["Ford", "Volvo", "BMW"] ---- Array Methods Python has a set of built-in methods that you can use on lists/arrays. Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the first item with the specified value reverse() Reverses the order of the list sort() Sorts the list | ||||||||||||||||||||||||||||||
---- Python Arrays Note: Python does not have built-in support for Arrays, but Python Lists can be used instead. Arrays Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to import a library, like the NumPy library. Arrays are used to store multiple values in one single variable: Example Get your own Python Server Create an array containing car names: cars = ["Ford", "Volvo", "BMW"] What is an Array? An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: car1 = "Ford" car2 = "Volvo" car3 = "BMW" However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Access the Elements of an Array You refer to an array element by referring to the index number. Example Get the value of the first array item: x = cars[0] Example Modify the value of the first array item: cars[0] = "Toyota" The Length of an Array Use the len() method to return the length of an array (the number of elements in an array). Example Return the number of elements in the cars array: x = len(cars) Note: The length of an array is always one more than the highest array index. Looping Array Elements You can use the for in loop to loop through all the elements of an array. Example Print each item in the cars array: for x in cars: print(x) Adding Array Elements You can use the append() method to add an element to an array. Example Add one more element to the cars array: cars.append("Honda") Removing Array Elements You can use the pop() method to remove an element from the array. Example Delete the second element of the cars array: cars.pop(1) You can also use the remove() method to remove an element from the array. Example Delete the element that has the value "Volvo": cars.remove("Volvo") Note: The list's remove() method only removes the first occurrence of the specified value. | ||||||||||||||||||||||||||||||
--------- mylist = ["apple", "banana", "cherry"] --- Python - List Methods List Methods Python has a set of built-in methods that you can use on lists. Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list sort() Sorts the list ---- Python Lists mylist = ["apple", "banana", "cherry"] List Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. Lists are created using square brackets: Example Get your own Python Server Create a List: thislist = ["apple", "banana", "cherry"] print(thislist) List Items List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc. Ordered When we say that lists are ordered, it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list. Note: There are some list methods that will change the order, but in general: the order of the items will not change. Changeable The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. Allow Duplicates Since lists are indexed, lists can have items with the same value: Example Lists allow duplicate values: thislist = ["apple", "banana", "cherry", "apple", "cherry"] print(thislist) List Length To determine how many items a list has, use the len() function: Example Print the number of items in the list: thislist = ["apple", "banana", "cherry"] print(len(thislist)) List Items - Data Types List items can be of any data type: Example String, int and boolean data types: list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3] list3 = [True, False, False] A list can contain different data types: Example A list with strings, integers and boolean values: list1 = ["abc", 34, True, 40, "male"] type() From Python's perspective, lists are defined as objects with the data type 'list': Example What is the data type of a list? mylist = ["apple", "banana", "cherry"] print(type(mylist)) The list() Constructor It is also possible to use the list() constructor when creating a new list. Example Using the list() constructor to make a List: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist) Python Collections (Arrays) There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members. Dictionary is a collection which is ordered** and changeable. No duplicate members. *Set items are unchangeable, but you can remove and/or add items whenever you like. **As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security. | ||||||||||||||||||||||||||||||
-------------- Python Sets myset = {"apple", "banana", "cherry"} Set Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which is unordered, unchangeable*, and unindexed. * Note: Set items are unchangeable, but you can remove items and add new items. Sets are written with curly brackets. Example Get your own Python Server Create a Set: thisset = {"apple", "banana", "cherry"} print(thisset) Note: Sets are unordered, so you cannot be sure in which order the items will appear. Set Items Set items are unordered, unchangeable, and do not allow duplicate values. Unordered Unordered means that the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key. Unchangeable Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can remove items and add new items. Duplicates Not Allowed Sets cannot have two items with the same value. Example Duplicate values will be ignored: thisset = {"apple", "banana", "cherry", "apple"} print(thisset) Note: The values True and 1 are considered the same value in sets, and are treated as duplicates: Example True and 1 is considered the same value: thisset = {"apple", "banana", "cherry", True, 1, 2} print(thisset) Get the Length of a Set To determine how many items a set has, use the len() function. Example Get the number of items in a set: thisset = {"apple", "banana", "cherry"} print(len(thisset)) Set Items - Data Types Set items can be of any data type: Example String, int and boolean data types: set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False} A set can contain different data types: Example A set with strings, integers and boolean values: set1 = {"abc", 34, True, 40, "male"} type() From Python's perspective, sets are defined as objects with the data type 'set': < class 'set' > Example What is the data type of a set? myset = {"apple", "banana", "cherry"} print(type(myset)) The set() Constructor It is also possible to use the set() constructor to make a set. Example Using the set() constructor to make a set: thisset = set(("apple", "banana", "cherry")) # note the double round-brackets print(thisset) Python Collections (Arrays) There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members. Dictionary is a collection which is ordered** and changeable. No duplicate members. *Set items are unchangeable, but you can remove items and add new items. **As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security. | ||||||||||||||||||||||||||||||
Set MethodsSet Methods Python has a set of built-in methods that you can use on sets. Method and Description add() Adds an element to the set clear() Removes all the elements from the set copy() Returns a copy of the set difference() Returns a set containing the difference between two or more sets difference_update() Removes the items in this set that are also included in another, specified set discard() Remove the specified item intersection() Returns a set, that is the intersection of two other sets intersection_update() Removes the items in this set that are not present in other, specified set(s) isdisjoint() Returns whether two sets have a intersection or not issubset() Returns whether another set contains this set or not issuperset() Returns whether this set contains another set or not pop() Removes an element from the set remove() Removes the specified element symmetric_difference() Returns a set with the symmetric differences of two sets symmetric_difference_update() inserts the symmetric differences from this set and another union() Return a set containing the union of sets update() Update the set with the union of this set and others | ||||||||||||||||||||||||||||||
Tuple MethodsPython Tuple Methods Tuples has two built-in methods that you can use: Method and Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets. Python Tuple Methods Example
Tuple Items with Data Types: Tuple items can be of any data type:
| ||||||||||||||||||||||||||||||