The for index in range(len(list)) loop executes the loop body with index first set to 0, then 1, then 2, etc. up to len(list) - 1. The previous value of index is ignored and overwritten. If you want index to start at iteration + 1, use the 2-argument form of range:
for index in range(iteration + 1, len(list)):
Answer from user2357112 on Stack OverflowI am pulling data from a dictionary and appending it to a list, but it appears that dictionary keys start at 1, not 0.
We have been taught to use for loops for this kind of task, but they initialize at 0. Can I start at 1? If not, what is an alternative? Thanks!
for i in range(len(dict)):
<code goes here>Python for loop start counter initialization - Stack Overflow
python - How to start a for loop from the end of a vector, and at the value 0 do something - Stack Overflow
Can a for loop start somewhere other than 0?
pygame - Python for loop does not start anymore at 0 - Stack Overflow
Videos
The for index in range(len(list)) loop executes the loop body with index first set to 0, then 1, then 2, etc. up to len(list) - 1. The previous value of index is ignored and overwritten. If you want index to start at iteration + 1, use the 2-argument form of range:
for index in range(iteration + 1, len(list)):
You really should be using enumerate for stuff like this, as you can loop through the index and the value at the same time (which will save you the hassle of using two for-loops).
for i, j in enumerate(list):
print i, j
Your inner loop is overriding the variable index that you defined in the first loop.
You can avoid index errors with sum(v[i+1:i+4]). You have to compare each element (if v[i] == 0) not the whole list.
v = [0, 5, 5, 0, 6, 6, 0, 7, 7 ]
for i in range(len(v) - 1, -1, -1):
if v[i] == 0 :
v[i] = sum(v[i+1:i+4])
print(v)
You can use itertools.accumulate on reversed list to get the sums and then switch to the sum in positions of where 0s exist in the original -
from itertools import accumulate
acc = list(accumulate(reversed(v))) #list of cumsums
sums = [j if i==0 else i for i,j in zip(reversed(v), acc)] #switch to cumsum where 0 exists in list
out = list(reversed(sums)) #reverse it back
print(out)
[36, 5, 5, 26, 6, 6, 14, 7, 7]
l = [a, b, c, d]
for x in l
print(x)Can this start at an index other than 0?
From the documentation:
range([start], stop[, step])
The start defaults to 0, the step can be whatever you want, except 0 and stop is your upper bound, it is not the number of iterations. So declare n to be whatever your upper bound is correctly and you will not have to add 1 to it.
e.g.
>>> for i in range(1, 7, 1): print(i)
...
1
2
3
4
5
6
>>> for i in range(1, 7, 2): print(i)
...
1
3
5
A nice feature, is that it works in reverse as well.
>>> for i in range(7, 0, -1): print(i)
...
7
6
5
4
3
2
1
If you aren't using it as an index but for something that can have positive or negative values, it still comes in handy:
>>> for i in range(2, -3, -1): print(i)
...
2
1
0
-1
-2
>>> for i in range(-2, 3, 1): print(i)
...
-2
-1
0
1
2
range(1, n+1) is not considered duplication, but I can see that this might become a hassle if you were going to change 1 to another number.
This removes the duplication using a generator:
for _ in (number+1 for number in range(5)):
print(_)
You can start a loop at whatever you want. The reason you see loops starting at zero often, is because they are looping through an array. Since the first item in an array is at index '0', it makes sense to start looping from 0 to access every item in an array.
You should use i = 0 in situations where iterating starting at zero would be natural, as previously stated this could include array indexing or similar. Personally I would say I use this style at least 90% of the time, as when modelling problems in the computer we mold them to use built in data structures, which usually start at 0. Our minds become use to working in this style.
Starting at i = 1 is more natural for modeling many problems while designing algorithms. For example, if you are given a problem such as person 1 is x years old, person 2 is y years old, and so on, indexing using the given numbers may make it easier to give an answer if asked something such as who is the youngest person in the list. Experience and experimentation will teach you if this is worthwhile, in my experience, this can be helpful in things such as programming competitions (like the ICPC), where algorithms must be developed quickly with not much time for debugging, and the algorithms can be very complex, so the clarity is important.
In other words it may be beneficial to waste this first index if it adds clarity, however experienced programmers quickly learn to understand both styles.
However, if you start at zero, remember to be aware that the arrays still start at zero, and you will need an n + 1 size array to represent n elements if you use indexing starting at 1.
Also be aware of your conditional in the for loop.
for (int i = 0; i < 10; i++) - Will loop 10 times
for (int i = 1; i <= 10; i++) - Will loop 10 times
It is basic, but a common source of errors that may be hard to track down, especially for beginning programmers.
I think you want something like this:
upper_limit = int(input("What's the upper limit? "))
total = 0
for num in range(upper_limit):
total = total + num
print("The result is:", total)
Be aware that, for range calls, the upper limit is excluded: if you type 3 as the input, it will iterate three times (with num set to 0, 1, and 2) - having upper_limit+1 as the argument of range will also include the upper_limit itself (which is why in your case the output was 6 instead of 3).
You shouldn't be adding kertoma in the loop, you should be adding the iteration variable from the range.
You need to use a different variable for the iteration than the variable you're adding to.
You don't have to write int(0), just 0. And tulos is an integer, so you don't have to write int(tulos).
The limit of the range should be kertomas, not kertomas+1, because range() doesn't include the end.
kertoma = int(input("Kuinka monta kierrosta?:"))
tulos = 0
for i in range(1, kertoma):
tulos = tulos + i
print("Kertymäksi saatiin:", tulos)
You can simply use slicing:
for item in I[1:]:
print(item)
And if you want indexing, use pythonic-style enumerate:
START = 1
for index, item in enumerate(I[START:], START):
print(item, index)
First thing is to remember that python uses zero indexing.
You can iterate throught the list except using the range function to get the indexes of the items you want or slices to get the elements.
What I think is becoming confusing here is that in your example, the values and the indexes are the same so to clarify I'll use this list as example:
I = ['a', 'b', 'c', 'd', 'e']
nI = len(I) # 5
The range function will allow you to iterate through the indexes:
for i in range(1, nI):
print(i)
# Prints:
# 1
# 2
# 3
# 4
If you want to access the values using the range function you should do it like this:
for index in range(1, nI):
i = I[index]
print(i)
# Prints:
# b
# c
# d
# e
You can also use array slicing to do that and you don't even need nI. Array slicing returns a new array with your slice.
The slice is done with the_list_reference[start:end:steps] where all three parameters are optional and:
start is the index of the first to be included in the slice
end is the index of the first element to be excluded from the slice
steps is how many steps for each next index starting from (as expected) the start (if steps is 2 and start with 1 it gets every odd index).
Example:
for i in I[1:]:
print(i)
# Prints:
# b
# c
# d
# e
