0

Given these variables:

a_4th =  6.08
delta_a = 0.052

I would like to create a list that contains:

a = [a_4th, a_5th, a_6th, a_7th ... ]

where:

a_5th = a_4th + delta_a
a_6th = a_5th + delta_a
a_7th = a_6th + delta_a

This code:

a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

for i in xrange (1,19):   # I would like the list to be 18 items long. 
                          # a[0] is defined in the previous line.
  a[i] = a[i-1] + delta_a 

is giving this error:

Traceback (most recent call last):
  File "so.py", line 8, in <module>
    a[i] = a[i-1] + delta_a 
IndexError: list assignment index out of range
2
  • 2
    a[i] doesn't exist past 0, try doing a.append()
    – depperm
    Jun 6, 2017 at 15:15
  • @depperm True... a[0] is the only value that exists in the list, thank you...
    – DavidC.
    Jun 6, 2017 at 17:00

4 Answers 4

5

How about this comprehension?

a_4th =  6.08
delta_a = 0.052
a = [a_4th + i * delta_a for i in range(20)]

Or your code, fixed:

a_4th =  6.08
delta_a = 0.052
a = [a_4th]
for i in xrange (1,19):
  a.append(a[i-1] + delta_a)  # or the elegant a.append(a[-1] + delta_a) kudos @Prune

Also note that appart from the speed benefits of the list comprehension, it also works for both Python 2.x and Python 3.x distributions making it easier to maintain.

1
  • Thank you very much for the answer, and for suggesting the comprehension list. However, I am still not used to this feature - do you know any good tutorial about the use of these ? Thanks a lot.
    – DavidC.
    Jun 6, 2017 at 17:00
3

Let's clean up your code:

a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

This wastes effort, both in reading and execution. Just initialize the list:

a = [a_4th]

As for the loop, you cannot assign to an element of the list that doesn't exist. You create new list elements with append, insert, concatenation, or other defined operations.

for i in xrange (1,19):   # I would like the list to be 18 items long. 
                          # a[0] is defined in the previous line.
  a.append( a[-1] + delta_a )

Yes, I removed the i from i-1; that introduces another possibility of error. Simply use the last (index minus-one) element of the list.

2
  • 1
    Thanks. This is part of writing maintainable code: don't compute something you can reference directly.
    – Prune
    Jun 6, 2017 at 15:24
  • @Prune thank you very much for your answer. 1) I agree this is a cleaner way of initializing. 2) True, the elements of the list do not exist, only a[0], that is why I cannot do a[i] = a[i-1] +... 3) Good idea, to refer simply as a[-1] for the last element of the list, instead of a[i-1]
    – DavidC.
    Jun 6, 2017 at 17:01
3

I would use a Python generator if I were you since it gives you extra expressiveness with the ability to express an "infinitely" large sequence.

def succession(initial, delta):
  while True:        
    yield initial
    # value, then, the next time you call 
    initial += delta

values_generator = succession(6.08, 0.052)

# later we decide how many values we want to consume from the generator
for i in range(20):
  print(next(values_generator))

Update:

Adding more explanation on generators. Generators are a mechanism provided by Python that allows to build efficient data processing pipelines.

Say you have a list of numbers from 0 to 100_000, and you want to apply some transformations to it like filtering, then mapping, and so on, if you use regular Python2 map and filter your solution won't scale well because in each step (filtering, mapping, etc) an entire new list of intermediate results with potentially many elements that might not even be used in the final result will be computed. The key idea of building these functional pipelines is that we want them to be combinators that is, small functions that we can combine to create yet new functions that later can be combined, but we don't want to pay a price in performance. Generators basically come to solve this in Python (in Clojure you have transducers and in Haskell lazy evaluation). With generators Python won't build the intermediate lists but to push one value on one end of the pipeline, transform it, and pop it out the other end, this for each element in the initial data set you wish to transform.

A simple example of a generator would be:

def trivial_generator():
  print "running until first yield..."
  yield 1
  print "running until second yield..."
  yield 2
  print "exiting..."


generator = trivial_generator()

result = generator.next()
print "got result ", result
result = generator.next()
print "got result ", result
generator.next()

if you run that you'll get:

running until first yield...
got result  1
running until second yield...
got result  2
exiting...
Traceback (most recent call last):
  File "foo.py", line 14, in <module>
    generator.next()
StopIteration

which illustrates the behavior of generators which is:

  1. You create one by calling a function that contains a yield
  2. Every time you call the .next() method on it, or pass it to the next(generator) function, the body of the generator will be executed until a yield is found
  3. When a yield is found, the value specified in the yield will be returned and the generator will stay paused until you call its .next() method again, at which point it will resume from the last point it was paused (notice that all the internal state of the generator is kept between calls)
  4. If you call .next() on a generator and no other yield is found (which means is the end of it) an StopIteration is raised (which is very convenient since is the exception a for loops expects to happen at the en d of an iterator)

In the example solution I used, I took advantage of the pause/resume capabilities of the generators, by putting the yield inside an infinite loop, I got a generator that will give me as many values I need efficiently.

3
  • Thank you very much for your generator solution. I am afraid I am a complete ignorant about the use of generators, so I do not understand very well the notation, why you use yield before while True ? Could you explain a bit what each line is doing ? Thank you so much
    – DavidC.
    Jun 6, 2017 at 17:01
  • 1
    Hi DavidC. I updated my answer with what I hope is a good explanation on generators.
    – Anler
    Jun 6, 2017 at 22:26
  • Thank you very much for the explanation - It's taking me some time to digest but step by step I'm getting it better. Thanks again
    – DavidC.
    Jun 19, 2017 at 9:53
1

The plain simple solution:

a = []
a.append(a_4th)
for i in xrange(1, 19):
    a.append(a[i-1] + delta_a)

but given your definition:

a_5th = a_4th + delta_a

a_6th = a_5th + delta_a

a_7th = a_6th + delta_a

we can much more simply think of it as:

a_5th = a_4th + (delta_a * 1)

a_6th = a_4th + (delta_a * 2)

a_7th = a_4th + (delta_a * 3)

and write it as a simple (and faster) list comprehension, cf Ev Kounis answer.

1
  • Thank you very much for pointing out that in fact this algorithm can be reduced to the first value a_4th + n times the constant.
    – DavidC.
    Jun 6, 2017 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.