Python has lists (and their contents can be anything). Example: a = [1] a.append('a') a.append(False) print(a) # [1, 'a', False] A list can carry a list of contentParticle in case you want particles = [] particles.append(oeFile.particle()) particles.append(oeFile.particle(material=2)) I'd probably structure the contentParticle outside of the oeFile class. Here's a full example, including two loops around the particles :) from dataclasses import astuple, dataclass @dataclass class contentParticle: identifier: str = "p" material: int = 0 index: int = 0 layer: int = 0xFF color: int = 0xFFFFFFFF xPos: float = 0.0 yPos: float = 0.0 xVel: float = 0.0 yVel: float = 0.0 xOrg: float = 0.0 yOrg: float = 0.0 angle: float = 0.0 angVel: float = 0.0 pressure: float = 0.0 content: str = "" particles = [] particles.append(contentParticle()) particles.append(contentParticle(material=2)) for particle in particles: print(particle.material) print("---") for particle in particles: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o = astuple(particle) print(b) Output: 0 2 --- 0 2 All the best :) Answer from lowerthansound on reddit.com
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ dataclasses.html
dataclasses โ€” Data Classes
4 weeks ago - Returns a tuple of Field objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises TypeError if not passed a dataclass or instance of one. Does not return pseudo-fields which are ClassVar or InitVar. ... Converts the dataclass obj to a dict (by using the factory function dict_factory). Each dataclass is converted to a dict of its fields, as name: value pairs. dataclasses, dicts, lists, and tuples are recursed into.
๐ŸŒ
Brown University
cs.brown.edu โ€บ courses โ€บ csci0111 โ€บ fall2020 โ€บ lectures โ€บ list-operations-and-dataclasses.html
List operations and dataclasses
class_item = TodoItem(date(2020, 11, 11), ["school", "class"], "Prepare for CSCI 0111", False) avocado_item = TodoItem(date(2020, 11, 16), ["home", "consumption"], "Eat avocado", False) birthday_item = TodoItem(date(2020, 11, 20), ["home", "friends"], "Buy present for friend", False) todo_list = [class_item, avocado_item, birthday_item] ... def test_past_due(): todo = TodoItem(date(2020, 11, 8), ["class"], "Prepare for CSCI 0111", False) test("old TODO", past_due(todo, date(2020, 11, 9), True) So we can access the components of a dataclass with dot-notation, just like we did in Pyret. As weโ€™ve seen, Python allows us to modify data.
Discussions

oop - How can I use a list[customClass] as type with @dataclass in Python 3.7.x - Stack Overflow
I have the following dataclasses. @dataclass class Package: '''Class for keeping track of one destination.''' _address: [] @dataclass class Destination: '''Class for keeping track of a More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to declare an array or a list in a Python @dataclass? - Stack Overflow
How can I declare an array (or at least list) in @dataclass? A something like below: from dataclasses import dataclass @dataclass class Test(): my_array: Array[ChildType] More on stackoverflow.com
๐ŸŒ stackoverflow.com
Uniquefy list of dataclass
Do you ever mutate them? If not, avoid making duplicates in the first place using a cache. But if you don't mutate them you may be better off with a namedtuple instead of a dataclass. If you do mutate them you won't be able to use unsafe_hash anyway, since it only applies at init. But you don't need O(N2) either; you can define your own hashmap. untested guess: def uniquify(data): seen = set() for item in data: if (itemhash := item.custom_hash_method()) not in seen: seen.add(itemhash) yield item More on reddit.com
๐ŸŒ r/learnpython
9
2
August 28, 2023
python 3.x - dictionary get method for list of dataclass objects - find dataclass with specific variable value in list of dataclasses - Stack Overflow
###It seems to me there has to be nicer way find a dataclass object than to loop through all to find the specific one. #My way, that I hope to improve: def changeValueOf(primaryKey): for item i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ make an array of dataclasses?
r/learnpython on Reddit: Make an array of dataclasses?
October 1, 2021 -

I have a nested dataclass as thus:

@dataclass()

class oeFile(object):

	@dataclass

	class contentParticle:

		identifier 	='p'

		material	= 0

		index 		= 0

		layer 		= 0xff

		color 		= 0xffffffff

		xPos		= 0.0

		yPos		= 0.0

		xVel		= 0.0

		yVel		= 0.0

		xOrg		= 0.0

		yOrg		= 0.0

		angle 		= 0.0

		angVel 		= 0.0

		pressure	= 0

		content		= ''

    particle: contentParticle = contentParticle()

contentOeFile = oeFile()

How can I set it up so that I can run something like this? Making a new instance of oeFile, or can I make an array something like particleData = oeFile.particle[1000]?

random spaghetti pseudocode roughly envisioning what I'm hoping for

while i <= len(particleData):
    (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) = particleData[i]
    i+=1

where a to o would be fed from a separate iterator pulling those values from a list, perhaps as an object that returns those values.

Yes I've been told pandas does database stuff easily but this is a programming exercise for me.

๐ŸŒ
Dataquest
dataquest.io โ€บ blog โ€บ how-to-use-python-data-classes
How to Use Python Data Classes (A Beginner's Guide) โ€“ Dataquest
May 12, 2025 - We didn't change the attributes of any object of the immutable classes, but we replaced the first element of the list with a different one, and the list is mutable. Keep in mind that all the attributes of the class should also be immutable in order to safely work with immutable data classes. The dataclasses module also supports inheritance, which means we can create a data class that uses the attributes of another data class.
๐ŸŒ
Real Python
realpython.com โ€บ python-data-classes
Data Classes in Python (Guide) โ€“ Real Python
March 8, 2024 - To show that it is possible to add your own .__repr__() method as well, we will violate the principle that it should return code that can recreate an object. Practicality beats purity after all. The following code adds a more concise representation of the Deck: ... from dataclasses import dataclass, field from typing import List @dataclass class Deck: cards: List[PlayingCard] = field(default_factory=make_french_deck) def __repr__(self): cards = ', '.join(f'{c!s}' for c in self.cards) return f'{self.__class__.__name__}({cards})'
๐ŸŒ
Blue Book
lyz-code.github.io โ€บ blue-book โ€บ coding โ€บ python โ€บ data_classes
Data classes - The Blue Book
January 19, 2025 - More complex default values can be defined through the use of functions. For example, the next snippet builds a French deck: from dataclasses import dataclass, field from typing import List RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() SUITS = 'โ™ฃ โ™ข โ™ก โ™ '.split() def make_french_deck(): return [PlayingCard(r, s) for s in SUITS for r in RANKS] @dataclass class PlayingCard: rank: str suit: str @dataclass class Deck: cards: List[PlayingCard] = field(default_factory=make_french_deck)
๐ŸŒ
Brown University
cs.brown.edu โ€บ courses โ€บ csci0111 โ€บ fall2019 โ€บ lectures โ€บ dataclasses.html
Python: dataclasses
class_item = TodoItem(date(2019, 11, 8), ["school", "class"], "Prepare for CSCI 0111", False) avocado_item = TodoItem(date(2019, 11, 13), ["home", "consumption"], "Eat avocado", False) birthday_item = TodoItem(date(2019, 11, 20), ["home", "friends"], "Buy present for friend", False) todo_list = [class_item, avocado_item, birthday_item] ... # in test_todo.py from todo import * import pytest def test_past_due(): assert past_due(TodoItem(date(2019, 11, 8), ["class"], "Prepare for CSCI 0111", False), date(2019, 11, 7)) == True ยท So we can access the components of a dataclass with dot-notation, just like we did in Pyret.
Find elsewhere
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-data-classes
Python Data Classes: A Comprehensive Tutorial | DataCamp
March 15, 2024 - So, to protect from accidental changes, it is recommended to use immutable objects such as tuples for field values. One last point we will cover is the order of fields in parent and child classes. Since data classes are regular classes, inheritance works as usual: @dataclass(frozen=True) class ImmutableWorkoutSession: exercises: List[Exercise] = field(default_factory=create_warmup) duration_minutes: int = 5 @dataclass(frozen=True) class CardioWorkoutSession(ImmutableWorkoutSession): pass
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ uniquefy list of dataclass
r/learnpython on Reddit: Uniquefy list of dataclass
August 28, 2023 -

I have a list of dataclass instances that i want to uniquefy. So i want to remove all duplicates while preserving order.

[3,1,1,4,5,6,6,3] -> [3,1,4,5,6]

I have two options.

Do list(dict.fromkeys(my_list)) which is O(N) but requires me to make the dataclass unsafe_hash=True (all of its attributes are hashable but the class is mutable).

Or write the O(N2) function that works also on unhashable types.

At the moment i am torn between which way to go.

๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ dataclass โ€“ easiest ever object-oriented programming in python
Dataclass - Easiest Ever Object-Oriented Programming In Python | Towards Data Science
March 5, 2025 - However, with the Python Dataclass, it is as easy as calling a built-in method. We can get a Python dictionary from a data class object. ... If we are only interested in the values of the fields, we can also get a tuple with all of them. This will also allow us to convert it to a list easily.
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ understanding python dataclasses
Understanding Python dataclasses - LogRocket Blog
January 17, 2025 - To enable comparison and sorting in a Python dataclass, you must pass the order property to @dataclass with the true value. This enables the default comparison functionality. Since we want to compare by population count, we must pass the population field to the sort_index property after initialization from inside the __post_innit__ method. You can also sort a list of objects ...
๐ŸŒ
Medium
medium.com โ€บ @sigmoid90 โ€บ python-tips-pretty-print-list-with-dataclass-df80dba1cc1f
Python tips: pretty print list with dataclass | by Vladprivalov | Medium
January 25, 2023 - This works well for dicts or lists which are serializable by default. Things get complicated when it comes to dataclasses. If we will try this method to print list of dataclass object we get error signaling that our dataclass is not serializable.
๐ŸŒ
Readthedocs
dataclass-wizard.readthedocs.io
Why Dataclass Wizard? โ€” Dataclass Wizard 0.39.1 documentation
Dataclass Wizard is a fast, well-tested serialization library for Python dataclasses. ... >>> from __future__ import annotations >>> from dataclasses import field >>> from dataclass_wizard import DataclassWizard ... >>> class MyClass(DataclassWizard, load_case='AUTO', dump_case='CAMEL'): ... my_str: str | None ... is_active_tuple: tuple[bool, ...] ... list_of_int: list[int] = field(default_factory=list) ...
๐ŸŒ
Python
peps.python.org โ€บ pep-0557
PEP 557 โ€“ Data Classes - Python Enhancement Proposals
November 3, 2023 - There were undesirable side effects of this decision, so the final decision is to disallow the 3 known built-in mutable types: list, dict, and set. For a complete discussion of this and other options, see [14]. Sometimes the generated __init__ method does not suffice. For example, suppose you wanted to have an object to store *args and **kwargs: @dataclass(init=False) class ArgHolder: args: List[Any] kwargs: Mapping[Any, Any] def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs a = ArgHolder(1, 2, three=3)
๐ŸŒ
Medium
elfi-y.medium.com โ€บ construct-your-object-with-python-data-class-bed53e202c4a
Construct Your Object with Python Data Class | by E.Y. | Medium
June 6, 2021 - @dataclass class Todo: todo_list: list = []ValueError: mutable default <class 'list'> for field todo_list is not allowed: use default_factory ยท On the other thread, the metadata parameter for the decorated class to add information to fields: @dataclass class Todo: date: str = field( metadata="date of the completion todo") ... To get the details of all the fields, we use the field method, which returns a tuple of Field objects that define the fields for this dataclass.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-41756.html
append str to list in dataclass
Dear community, I'm trying to append str to a list, which is in a dataclass. I'm totally new to dataclasses. I used to use a textfile for storing strings. Then I read about dataclasses for storing data. What is the simplest way for appending strin...
Top answer
1 of 2
31

The answer depends on whether or not you have access to an object of the class.

Just using the class

If you only have access to the class, then you can use dataclasses.fields(C) which returns a list of field objects (each of which has a .name property):

[field.name for field in dataclasses.fields(C)]

From an existing object

If you have a constructed object of the class, then you have two additional options:

  1. Use dataclasses.fields on the object:
[field.name for field in dataclasses.fields(obj)]
  1. Use dataclasses.asdict(obj) (as pointed out by this answer) which returns a dictionary from field name to field value. It sounds like you are only interested in the .keys() of the dictionary:
dataclasses.asdict(obj).keys()       # gives a dict_keys object
list(dataclasses.asdict(obj).keys()) # gives a list
list(dataclasses.asdict(obj))        # same 

Full example

Here are all of the options using your example:

from dataclasses import dataclass, fields, asdict


@dataclass
class C:
    x: int
    y: int
    z: int
    t: int

# from the class
print([field.name for field in fields(C)])

# using an object
obj = C(1, 2, 3, 4)

print([field.name for field in fields(obj)])
print(asdict(obj).keys())
print(list(asdict(obj).keys()))
print(list(asdict(obj)))

Output:

['x', 'y', 'z', 't']
['x', 'y', 'z', 't']
dict_keys(['x', 'y', 'z', 't'])
['x', 'y', 'z', 't']
['x', 'y', 'z', 't']
2 of 2
14

You can use the asdict method of the dataclasses module. For example:

from dataclasses import dataclass, asdict


@dataclass
class Person:
    age: int
    name: str


adam = Person(25, 'Adam')

# if you want the keys

print(asdict(adam).keys()) # dict_keys(['age', 'name'])

# if you want the values

print(asdict(adam).values()) # dict_values([25, 'Adam'])

Both methods above return a View object which you can iterate on, or you can convert it to list using list(...).