Because of aliasing; the line fish[i] = fish_value
is bad practice, fish_value
gets overwritten each time you loop; then fish[i] = fish_value
just assigns a shallow copy into fish[i]
, which is not what you want.
But really you can avoid the loop with a dict comprehension.
Anyway, better coding practice is to declare your own Fish
class with members weight, visual, step
, as below. Note how:
- we use
zip()
function to combine the separate w,v,s
lists into a tuple-of-list.
- Then the syntax
*wvs
unpacks each tuple into three separate values ('weight', 'visual', 'step'). This is called tuple unpacking, it saves you needing another loop, or indexing.
- a custom
__repr__()
method (with optional ASCII art) makes each object user-legible. (Strictly we should be overriding __str__
rather than __repr__
, but this works)
Code:
class Fish():
def __init__(self, weight=None, visual=None, step=None):
self.weight = weight
self.visual = visual
self.step = step
def __repr__(self):
"""Custom fishy __repr__ method, with ASCII picture"""
return f'<º)))< [ Weight: {self.weight}, visual: {self.visual}, step: {self.step} ]'
# define whatever other methods you need on 'Fish' object...
# Now create several Fish'es...
swarm = [ Fish(*wvs) for wvs in zip([3.1, 3, 4.1, 10], [2, 4, 10, 3], [1, 2, 5, 1.5]) ]
# zip() function combines the lists into a tuple-of-list. `*wvs` unpacks each tuple into three separate values ('weight', 'visual', 'step')
# See what we created...
>>> swarm
[<º)))< [ Weight: 3.1, visual: 2, step: 1 ], <º)))< [ Weight: 3, visual: 4, step: 2 ], <º)))< [ Weight: 4.1, visual: 10, step: 5 ], <º)))< [ Weight: 10, visual: 3, step: 1.5 ]]
# ... or for prettier output...
>>> for f in swarm: print(f)
<º)))< [ Weight: 3.1, visual: 2, step: 1 ]
<º)))< [ Weight: 3, visual: 4, step: 2 ]
<º)))< [ Weight: 4.1, visual: 10, step: 5 ]
<º)))< [ Weight: 10, visual: 3, step: 1.5 ]