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)
Answer from Mastermind on Stack OverflowYou 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
The straightforward answer
Just use slicing:
>>> l = ['a','b','c','d']
>>> for i in l[1:]:
... print(i)
...
b
c
d
It will generate a new list with the items before 1 removed:
>>> l[1:]
['b', 'c', 'd']
A more efficient alternative
Alternatively, if your list is huge, or you are going to slice the list a lot of times, you can use itertools.islice(). It returns an iterator, avoiding copying the entire rest of the list, saving memory:
>>> import itertools
>>> s = itertools.islice(l, 1, None)
>>> for i in s:
... print(i)
...
b
c
d
Also note that, since it returns an interator, you can iterate over it only once:
>>> import itertools
>>> s = itertools.islice(l, 1, None)
>>> for i in s:
... print(i)
...
b
c
d
>>> for i in s:
... print(i)
>>>
How to choose
I find slicing clearer/more pleasant to read but itertools.islice() can be more efficient. I would use slicing most of the time, relying on itertools.islice() when my list has thousands of items, or when I iterate over hundreds of different slices.
My 5 cent:
start_from = 'b'
for val in l[l.index(start_from ) if start_from in l else 0:]:
print val
Can a for loop start somewhere other than 0?
python - Enumerate list of elements starting from the second element - Stack Overflow
iteration - Start index for iterating Python list - Stack Overflow
How do you start a for loop at 1 instead of 0?
Videos
Use itertools.islice() to slice skipping the first.
from itertools import islice
for (script, location) in islice(self.device.scripts, 1, None):
pass # do stuff
Just slice it.
for script, location in self.device.scripts[1:]:
pass
For your second question, you don't need to worry about any IndexError since slicing returns an empty list when it's out of range.
l = [a, b, c, d]
for x in l
print(x)Can this start at an index other than 0?
When you call
enumerate(list_of_lines, start=1)
, the pairs that it generates are not
1 ['b', 'b', 'b', 'b', 'b']
2 ['c', 'c', 'c', 'c', 'c']
, but rather
1 ['a', 'a', 'a', 'a']
2 ['b', 'b', 'b', 'b', 'b']
3 ['c', 'c', 'c', 'c', 'c']
That is, the start value indicates what the first index used should be, not what the first element to use is.
Perhaps an alternate way of doing this would be as follows:
for (index, item) in list(enumerate(list_of_lines))[1:]:
list_of_lines[index][1:3] = [''.join(item[1:3])]
You can explicitly create an iterable with the iter() builtin, then call `next(iterable) to consume one item. Final result is something like this:
line_iter = iter(list_of_lines[:])
# consume first item from iterable
next(line_iter)
for index, item in enumerate(line_iter, start=1):
list_of_lines[index][1:3] = [''.join(item[1:3])]
Note the slice on the first line, in general it's a bad idea to mutate the thing you're iterating over, so the slice just clones the list before constructing the iterator, so the original list_of_lines can be safely mutated.
I 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>You could hack a generator expression
def mymethod():
return [[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]]
mylist = mymethod()
for thing in (i[1] for i in mylist):
print thing
# this bit is meant to be outside the for loop,
# I mean it to represent the last value thing was in the for
if thing:
print thing
If you want to get the second column of an array, you could use a list comprehension, like so:
a = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9,10,11,12 ],
[13,14,15,16 ] ]
second_column = [ row[1] for row in a ]
# you get [2, 6, 10, 14]
You can wrap this up in a function:
def get_column ( array, column_number ):
try:
return [row[column_number] for row in array]
except IndexError:
print ("Not enough columns!")
raise # Raise the exception again as we haven't dealt with the issue.
fourth_column = get_column(a,3)
# you get [4, 8, 12, 16]
tenth_column = get_column(a,9)
# You requested the tenth column of a 4-column array, so you get the "not enough columns!" message.
Though really, if you're working with rectangular arrays of numbers, you want to be using numpy arrays, not lists of lists of numbers.
Or, by Lattyware's implied request, a generator version:
def column_iterator ( array, column_number ):
try:
for row in array:
yield row[column_number]
except IndexError:
print ("Not enough columns!")
raise
Usage is just like a normal list:
>>> for item in column_iterator(a,1):
... print(item)
...
2
6
10
14
>>>
The generator-nature is evident by:
>>> b = column_iterator(a,1)
>>> b.next()
2
>>> b.next()
6
>>> b.next()
10
>>> b.next()
14
edit: forgot to mention I want the indeces not just the items
the methods I can think of are:
for i in range(len(arr) - 1)
for i, e in enumerate(arr[:len(arr) - 1])
I know range(len(arr)) is frowned upon, but I don't see how it's worse than enumerate in this case. In fact using enumerate on a shortened list and calling len to find the second to last element of that list seems extremely clunky and far less readable.
What's the best practice for doing this?