Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Container Types: A Quick Guide
1
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. [Image: 1f682.png][Image: 1f683.png][Image: 1f683.png][Image: 1f683.png]

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 [Image: 1f4e6.png]. These containers make it easy for you to store, manage and manipulate your data effectively and efficiently. [Image: 1f603.png]

You might be wondering what makes each container unique. Well, they all serve different purposes and have distinct characteristics.
  • For instance, lists are mutable and ordered, allowing you to add, remove, or modify elements.

  • Tuples, on the other hand, are immutable and ordered, which means once created, their elements cannot be changed [Image: 2728.png].

  • Dictionaries are mutable and store key-value pairs, making it efficient for data retrieval.

  • Lastly, sets and frozensets are unordered collections, with sets being mutable and frozensets immutable.

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

[Image: image-301.png]

You might be wondering about Python’s built-in container types. Let’s dive into them and see how useful they can be! [Image: 1f603.png]

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:
  • Code:
    append(x)
    : Adds x to the end of the list

  • Code:
    extend(iterable)
    : Adds items from iterable to the list

  • Code:
    insert(i, x)
    : Inserts x at index i

  • Code:
    remove(x)
    : Removes the first item with the value
    Code:
    x

Feel free to dive into our full guide on lists here:

[Image: image-298.png]

[Image: 1f4a1.png] Recommended: The Ultimate Guide to Python Lists

Tuple

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:
  • Code:
    count(x)
    : Counts the occurrences of
    Code:
    x
    in the tuple

  • Code:
    index(x)
    : Finds the index of the first occurrence of
    Code:
    x

Again, we have created a full guide on tuples here:

[Image: image-299.png]

[Image: 1f4a1.png] Recommended: The Ultimate Guide to Python Tuples

Set

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:
  • Code:
    add(x)
    : Adds x to the set

  • Code:
    remove(x)
    : Removes x from the set

  • Code:
    union(s)
    : Returns the union of the set and s

  • Code:
    intersection(s)
    : Returns the intersection of the set and s

[Image: 1f4a1.png] Recommended: The Ultimate Guide to Python Sets

Dict

The dictionary, or
Code:
dict
, is a mutable mapping type. This container allows you to store key-value pairs efficiently.

Example of creating a
Code:
dict
:

Code:
your_dict = {'a': 1, 'b': 2, 'c': 3}

Some helpful dict methods are:
  • Code:
    get(key, default)
    : Gets the value for the key or returns the default value if not found

  • Code:
    update(iterable)
    : Merges the key-value pairs from iterable into the dictionary

  • Code:
    pop(key, default)
    : Removes and returns the value for the key or returns the default value if not found

[Image: 1f4a1.png] Recommended: The Ultimate Guide to Python Dictionaries

That’s a quick rundown of Python’s basic built-in container types!

Advanced Container Types from Collections Module

[Image: image-302.png]

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
module comes to the rescue [Image: 1f4aa.png].

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? [Image: 1f914.png] The
Code:
namedtuple
class is your answer! Namedtuples are similar to regular tuples, but each element has a name for better readability and maintenance [Image: 1f4a1.png]:

Code:
from collections import namedtuple Person = namedtuple("Person", ["name", "age", "city"]) person1 = Person("Alice", 30, "New York") print(person1.name) # Output: Alice

Now, you can access tuple elements by name instead of index, making your code more readable and less error-prone [Image: 1f44c.png].

[Image: 1f4a1.png] Recommended: Python Named Tuple Methods

Deque

If you need a high-performance, double-ended queue, look no further than the
Code:
deque
class. Deques allow you to efficiently append or pop items from both ends of the queue, which can be useful in various applications, such as maintaining a fixed-size history of events [Image: 1f570.png]:

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 [Image: 1f60e.png].

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 [Image: 1f4da.png]:

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 dictionary

With ChainMap, you can work with multiple dictionaries as if they were one, simplifying your code and making it more efficient [Image: 1f609.png].

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 [Image: 1f4af.png]:

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 [Image: 1f680.png].

OrderedDict

If you need a dictionary that maintains the insertion order of items, the
Code:
OrderedDict
class is perfect for you! Although Python 3.7+ dictionaries maintain order by default,
Code:
OrderedDict
can be useful when working with older versions or when you want to explicitly show that order matters [Image: 1f4dd.png]:

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
ensures that your code behaves consistently across Python versions and emphasizes the importance of insertion order [Image: 1f31f.png].

Defaultdict

When working with dictionaries, do you often find yourself initializing default values? The
Code:
defaultdict
class can automate that for you! Just provide a default factory function, and
Code:
defaultdict
will create default values for missing keys on the fly [Image: 2728.png]:

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
, you can keep your code free of repetitive default value initializations and make your code more Pythonic [Image: 1f40d.png].

[Image: image-303.png]

Feel free to check out our cheat sheets on Python, OpenAI, and Blockchain topics:

Also, you may enjoy this article:

[Image: 1f4a1.png] Recommended: 21 Most Profitable Programming Languages
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: