Reputation:
I want to create a loop that creates an object if a certain condition is met and then adding it to a list. However, I am unsure how to uniquely name these objects so they can be used/referenced later on. For example something like this:
favNumbers = []
numbers = [6, 21, 5, 22]
class favNumber(object):
def __init__(self, value):
self.value = value
for i in numbers:
if i % 2 == 0:
unique_name_for_object = favNumber(i)
favNumbers.append(unique_name_for_object)
How would I gave the favNumber
objects a unique name?
I was thinking of somehow naming them number1, number2, number3... but I think dynamically naming them would be a bad idea.
Is there a way of doing it without dynamically naming them? It seems as if that would be impossible but I am unsure as to how else I could accomplish it.
Upvotes: 0
Views: 448
Reputation: 1578
If you simply want to generate a list, you can use a list comprehension:
favNumbers = [favNumber(i) for i in numbers if n % 2 == 0]
The last expression (if n % n == 0
) acts as a filter. To access the values, you use an index (eg. favNumbers[0]
for the first item), or loop through the list like you did with numbers
.
As someone pointed out in the comments, {}
is a dict
and cannot be appended to. You can however insert items given a key (which might as well be the integer i
, although it usually makes more sense to use lists when the keys are consecutive non-negative integers).
for i in numbers:
if n % 2 == 0:
favNumbers[i] = favNumber(i)
It can also be done with a dictionary comprehension:
favNumbers = { i : favNumber(i) for i in numbers if n % n == 0 }
I'll update the answer if you provide additional context.
Upvotes: 0
Reputation: 5486
There is no need to name the instances. Just try this one
favNumbers = []
numbers = [6, 21, 5, 22]
class favNumber(object):
def __init__(self, value):
self.value = value
for i in numbers:
if i % 2 == 0:
favNumbers.append( favNumber(i) )
Now, favNumbers
is a list of all created instances. If you want to get the value
ot the each instance, just type
for fn in favNumbers:
print(fn.value)
Upvotes: 1