Knowing Python data container types #Python #Programming

There are a lot of container types available in the Python standard library, and it can be confusing sometimes to keep track of them all.

James Bennett goes through and discusses each one. James’ advice:

  • Use a list for most cases where you just want an iterable/indexable sequence.
  • Use a tuple as a struct-like type where multiple instances will have the same structure, but consider using named tuples to make that structure clearer (a lot of people don’t like named tuples because of the fact that they support iteration and numeric indexing as well as named field access, but I don’t personally mind this).
  • Use dict for key-value mappings.
  • Use set when uniqueness matters, though this is not super common; most of the value of sets is in the union/intersection/etc. operations they support.
  • Don’t use dataclass as a “super-tuple”; if what you really want is just a plain data container with named field access, just use a named tuple. Use dataclass when you also want the result to be an ordinary mutable Python class (tuples are immutable) with potentially extra behavior attached via methods.
  • Avoid most of the other container types unless you know they’re the right thing for your specific use case. And if you’re not sure whether they’re right, they aren’t; you generally will just know when one of them is the right fit (for example, collections.Counter is very useful for the exact specific thing it does, and not really useful at all for anything else).

See the whole discussion in the post here.


Have an amazing project to share? The Electronics Show and Tell is every Wednesday at 7:30pm ET! To join, head over to YouTube and check out the show’s live chat and our Discord!

Join us every Wednesday night at 8pm ET for Ask an Engineer!

Join over 38,000+ makers on Adafruit’s Discord channels and be part of the community! http://adafru.it/discord

CircuitPython – The easiest way to program microcontrollers – CircuitPython.org


New Products – Adafruit Industries – Makers, hackers, artists, designers and engineers! — New Products 11/15/2024 Featuring Adafruit bq25185 USB / DC / Solar Charger with 3.3V Buck Board! (Video)

Python for Microcontrollers – Adafruit Daily — Python on Microcontrollers Newsletter: A New Arduino MicroPython Package Manager, How-Tos and Much More! #CircuitPython #Python #micropython @ThePSF @Raspberry_Pi

EYE on NPI – Adafruit Daily — EYE on NPI Maxim’s Himalaya uSLIC Step-Down Power Module #EyeOnNPI @maximintegrated @digikey

Adafruit IoT Monthly — The 2024 Recap Issue!

Maker Business – Adafruit Daily — Apple to build another chip at TSMC Arizona

Electronics – Adafruit Daily — SMT Tip – Stop moving around!

Get the only spam-free daily newsletter about wearables, running a "maker business", electronic tips and more! Subscribe at AdafruitDaily.com !


No Comments

No comments yet.

Sorry, the comment form is closed at this time.