-5

Is there some way to simplify this code? Maybe using def or a for loop or lists or something? Thank you!

c=0
c2=0
c3=0
c4=0
c5=0
c6=0
c7=0
c8=0
c9=0
c10=0
c11=0
c12=0
c13=0
c14=0
c15=0
c16=0
c17=0
c18=0
c19=0
c20=0
c21=0
c22=0
c23=0
c24=0
c25=0
c26=0
julia
  • 11
  • 2

2 Answers2

3

I would much rather use a dictionary here:

>>> d = {"c{}".format(val): 0 for val in range(27)}
>>> d
{'c19': 0, 'c18': 0, 'c13': 0, 'c12': 0, 'c11': 0, 'c10': 0, 'c17': 0, 'c16': 0, 'c15': 0, 'c14': 0, 'c9': 0, 'c8': 0, 'c3': 0, 'c2': 0, 'c1': 0, 'c0': 0, 'c7': 0, 'c6': 0, 'c5': 0, 'c4': 0, 'c22': 0, 'c23': 0, 'c20': 0, 'c21': 0, 'c26': 0, 'c24': 0, 'c25': 0}
>>> d.get('c15')
0
>>> d.get('c10000')
None
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • 1
    I'd love to hear why. I considered recommending a dictionary, but I felt that since the naming was sequential integers anyways, we didn't really gain anything, but used more memory – Patrick Haugh Oct 25 '16 at 00:49
  • 1
    @PatrickHaugh For the sole fact that whatever you want to do after, the chances are that the dictionary will outperform. TBH though, there is nowhere near enough information here and I almost did not want to answer and still might delete because this question is horrible. – idjaw Oct 25 '16 at 00:52
  • 2
    Yeah, this seems like a pretty straight-forward XY problem – Patrick Haugh Oct 25 '16 at 00:54
1

There are a couple of solutions. What are you using all these variables for? The best solution is probably to put them in a list. So:

c = [0 for _ in range(number_of_variables)]

Then you access them like c[0] c[26] etc

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • 2
    ... or `c = [0] * number_of_variables` – Warren Weckesser Oct 25 '16 at 00:36
  • 2
    @WarrenWeckesser I'm always a little leery of `[item] * n` It interacts with lists in an unintuitive way and tends to trip people up, especially new coders who don't necessarily understand the difference between mutable and immutable objects. – Patrick Haugh Oct 25 '16 at 00:38