![]() |
|
[Tut] Python Container Types: A Quick Guide - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Container Types: A Quick Guide (/thread-101073.html) |
[Tut] Python Container Types: A Quick Guide - xSicKxBot - 04-29-2023 Python Container Types: A Quick Guide 5/5 – (1 vote) If you’re working with Python, most of the data structures you’ll think about are container types. ![]() ![]() ![]() ![]() These containers are special data structures that hold and manage collections of elements. Python’s most commonly used built-in container types include tuples, lists, dictionaries, sets, and frozensets . These containers make it easy for you to store, manage and manipulate your data effectively and efficiently. ![]() You might be wondering what makes each container unique. Well, they all serve different purposes and have distinct characteristics.
As you explore Python, understanding these container types is essential, as they provide a foundation for organizing and manipulating your data. Basic Built-In Container Types ![]() You might be wondering about Python’s built-in container types. Let’s dive into them and see how useful they can be! ![]() List A List is a mutable sequence type in Python. It allows you to store a collection of objects in a defined order. With lists, you can add, remove or change items easily. Example of creating a list: Code: your_list = [1, 2, 3, 4]Some handy list methods are:
Feel free to dive into our full guide on lists here: ![]() Recommended: The Ultimate Guide to Python ListsTuple A Tuple is an immutable sequence type. It’s similar to a list but cannot be modified once created. This makes tuples ideal for storing fixed sets of data. Example of creating a tuple: Code: your_tuple = (1, 2, 3)Since it’s immutable, fewer methods are available compared to lists:
Again, we have created a full guide on tuples here: ![]() Recommended: The Ultimate Guide to Python TuplesSet A set is an unordered collection of unique elements. Sets can help you manage distinct items, and they can be mutable or immutable (frozenset). Example of creating a set: Code: your_set = {1, 2, 3, 3}A few useful set operations include:
Recommended: The Ultimate Guide to Python SetsDict The dictionary, or Code: dictExample of creating a Code: dictCode: your_dict = {'a': 1, 'b': 2, 'c': 3}Some helpful dict methods are:
Recommended: The Ultimate Guide to Python DictionariesThat’s a quick rundown of Python’s basic built-in container types! Advanced Container Types from Collections Module ![]() The Python built-in containers, such as list, tuple, and dictionary, can be sufficient for many cases. However, when you need more specialized or high-performance containers, the Code: collections .Let’s explore some of these advanced container types: Namedtuple Ever struggled with using tuples to store data, leading to unreadable and error-prone code? The Code: namedtuple :Code: from collections import namedtuple Person = namedtuple("Person", ["name", "age", "city"])
person1 = Person("Alice", 30, "New York")
print(person1.name) # Output: AliceNow, you can access tuple elements by name instead of index, making your code more readable and less error-prone . Recommended: Python Named Tuple MethodsDeque If you need a high-performance, double-ended queue, look no further than the Code: deque :Code: from collections import deque dq = deque(maxlen=3)
for i in range(5): dq.append(i) print(dq) # Output:
# deque([0], maxlen=3)
# deque([0, 1], maxlen=3)
# deque([0, 1, 2], maxlen=3)
# deque([1, 2, 3], maxlen=3)
# deque([2, 3, 4], maxlen=3)With deque, you can keep your data structures efficient and clean .ChainMap Do you have multiple dictionaries that you want to treat as a single unit? The ChainMap class can help! It allows you to link several mappings together, making it easy to search, update or delete items across dictionaries :Code: from collections import ChainMap dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
chain_map = ChainMap(dict1, dict2)
print(chain_map["b"]) # Output: 2, as it takes the value from the first dictionaryWith ChainMap, you can work with multiple dictionaries as if they were one, simplifying your code and making it more efficient .Counter Counting items in a collection can be a repetitive task. Luckily, the Counter class can help you keep track of elements and their counts with ease :Code: from collections import Counter data = [1, 2, 3, 2, 1, 3, 1, 1]
count = Counter(data)
print(count) # Output: Counter({1: 4, 2: 2, 3: 2})Now you can easily count items in your collections, making your code more concise and efficient .OrderedDict If you need a dictionary that maintains the insertion order of items, the Code: OrderedDictCode: OrderedDict :Code: from collections import OrderedDict od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
print(list(od.keys())) # Output: ['a', 'b', 'c']Code: OrderedDict .Defaultdict When working with dictionaries, do you often find yourself initializing default values? The Code: defaultdictCode: defaultdict :Code: from collections import defaultdict dd = defaultdict(list)
dd["a"].append(1)
dd["b"].append(2)
dd["a"].append(3) print(dd) # Output: defaultdict(, {'a': [1, 3], 'b': [2]})With Code: defaultdict .![]() Feel free to check out our cheat sheets on Python, OpenAI, and Blockchain topics: Also, you may enjoy this article: Recommended: 21 Most Profitable Programming Languages
|