0

I have a piece of code:

binCounts = []
for i in range(len(bins)):
    binCounts.append(0)

where bins is an array that looks something like this:

['chrY', '28626328', '3064930174', '28718777', '92449', '49911'], ['chrY', '28718777', '3065022623', '28797881', '79104', '49911'], ['chrY', '28797881', '3065101727', '59373566', '30575685', '49912']]

When I run just range(len(bins)) in Python's interactive mode, I get:

[0, 1, 2]

but when I test the whole piece of code, I'm getting

[0,0,0]

I believe I should be getting

[0, 1, 2, 0] 

This is resulting in a Division by Zero error later on down the line. Why is this happening? How can I fix it? I appreciate your guidance!

mfk534
  • 719
  • 1
  • 9
  • 21

2 Answers2

3

Your code add 0 to list 3 times, so you are getting exactly what you asked. Maybe you wanted to do:

binCounts = []
for i in range(len(bins)):
    binCounts.append(i)
binCounts.append(0)
ISanych
  • 21,590
  • 4
  • 32
  • 52
  • Thanks very much! I had to put a space between 'binCounts.append(i)' and 'binCounts.append(0)' and then it worked like a charm. I appreciate it. – mfk534 Jul 22 '15 at 16:58
2

You are receiving a list of zeros because of this line:

binCounts.append(0)

Each time through the loop, you append a zero to binCount


If your goal is to put a zero only at the end of the list, pull that line out of your for loop

for i in range(len(bins)):
    # Logic
binCounts.append(0)

It appears you are creating a list with values in the range 0 through the length of bins. You can do this without for loop:

binCounts = range(len(bins))
binCounts.append(0)

At the end of these two lines, binCounts will be:

[0, 1, 2, 0]
Andy
  • 49,085
  • 60
  • 166
  • 233
  • Thanks very much. Removing the for loop makes great sense and I appreciate that suggestion. I'm still getting used to the indentation formalities of Python and it seems that's where most of my problems come from. Could you recommend a good text editor that won't slip in false tabs and the like? (I use TextWrangler which is pretty good, but maybe there is something made specifically for Python?) – mfk534 Jul 22 '15 at 16:57
  • Python has a number of [IDEs](https://wiki.python.org/moin/IntegratedDevelopmentEnvironments) you can choose from. They range from stand alone applications dedicated to Python development to plugins for Eclipse, Visual studio or others. This [answer](http://stackoverflow.com/questions/81584/what-ide-to-use-for-python) is also helpful – Andy Jul 22 '15 at 17:01
  • 2
    @mfk534, try pycharm - https://www.jetbrains.com/pycharm/download/ - even community edition is very good – ISanych Jul 22 '15 at 17:01