0

I'm trying to do a for loop. Introduce a value (p) into an empty list. I want to do a kind of vector that save me all source values of the math operations.

lista=list()
for index in len(lista+1):
 lista.append(p)
 index=index+1
print lista

Thx for your help

5
  • 3
    what is the issue you are facing? Commented May 3, 2013 at 23:07
  • Instead of keeping track of the loop iteration yourself, use docs.python.org/2/library/functions.html#enumerate Commented May 3, 2013 at 23:07
  • What's the point of the loop here? Are you trying to add more than one value? Adding a single value to a list is done simply by calling lista.append(p). Commented May 3, 2013 at 23:16
  • 1
    Or, if you want to add n copies of a value, that's just lista.extend(p * n). Commented May 3, 2013 at 23:22
  • You are (1) trying to add an int to a list (lista+1) and (2) trying to iterate over an int (len(lista+1)). Neither of these makes sense, and both result in errors. Commented May 3, 2013 at 23:24

4 Answers 4

2

If you just want to insert a value into an empty list it should look like this:

ps = []      # create the empty list
ps.append(p) # add the value p

or you could just do this which gives the same result ps = [p]

If you want to insert it n-times you can use a for loop like this:

ps = []
for i in range(n):
  ps.append(p)

or just do this which gives the same result ps = n * [p]

Sign up to request clarification or add additional context in comments.

2 Comments

p have different values every time that the program did an operation
There is no way for p to change in your loop. We would need more context information to help you with this.
2

you can try this:

lista = [i*i for i in range(N)]
print lista

or use:

for i in range(N)
   lista.append(i*i)
print lista

1 Comment

but I don't know the number of data could be 100 or 1000. It depends the time of running of the Program.
1

You should be doing for index in range(len(lista) + 1): instead of for index in len(lista+1):

To simplify your code, you can also do:

lista = list()
[p] * (len(lista) + 1)

1 Comment

maybe you mean for index in range(len(lista)+1)?
0
lista=list()
for index in range(len(lista)):
 lista.insert(p)
 index=index+1
print lista

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.