Python for loops has index for counter - python

Hello I'm beginner in Python and trying to read a part of a code with for loop but can't understand it, does any body knows how there is index over loop counter? Thanks
updateNodeNbrs = []
for a in nodeData:
updateNodeNbrs.append(a[0])

You're iterating directly over the elements of nodeData, so there is no need for an index. The current element is designated by a.
This is equivalent to:
updateNodeNbrs = []
for i in range(len(nodeData)):
updateNodeNbrs.append(nodeData[i][0])
Although the original code is more pythonic.
If you wanted to make the index appear, you could transform the code with enumerate to:
updateNodeNbrs = []
for i, a in enumerate(nodeData):
updateNodeNbrs.append(a[0])
And here, i would be the index of element a, and you could use it in the loop.

See same question here
If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate function. For example
l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
print "index", i, "is", fruit

Related

Python Beginner Question: how does this code work? [duplicate]

Can someone explain the last line of this Python code snippet to me?
Cell is just another class. I don't understand how the for loop is being used to store Cell objects into the Column object.
class Column(object):
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.
The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
Explanation:
To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.
Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.
For instance:
myList = []
for i in range(10):
myList.append(i)
is equivalent to
myList = [i for i in range(10)]
List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.
This example only collects even numbered values in the list:
myList = []
for i in range(10):
if i%2 == 0: # could be written as "if not i%2" more tersely
myList.append(i)
and the equivalent list comprehension:
myList = [i for i in range(10) if i%2 == 0]
Two final notes:
You can have "nested" list comrehensions, but they quickly become hard to comprehend :)
List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.
Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:
data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]
gives:
new_data
[3.0, 7.4, 8.2]
It is the same as if you did this:
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
This is called a list comprehension.

Removing last list element by popping

I have the following piece of Python code where I am trying to empty out list A by removing one element at a time starting from the end. I cannot seem to reduce the list to an empty one and I would like to know why not. Any insight would be extremely appreciated.
A = [3,4,5,6,2]
for i in A:
A.pop()
var = [3,4,5,6,2]
for x in range(len(var)):
a = var.pop(-1)
print(a)
or reverse a list
var = var[::-1]
This issue you are facing because you are trying to iterate the loop from first element and trying to remove the last element of the list. at one pint for loop runs out of element in a list hence it stops and you don't get empty list.
The proper solution will be to reverse iterate through the list and remove the elements.
Sample Code :
A = [3,4,5,6,2]
for i in range( len(A) -1 , -1, -1):
A.pop()
print (A)
You can try this:
A = [3,4,5,6,2]
for a in range(len(A)):
A.pop(-1)
Output:
>>> A
[]
You can also use a list comprehension instead of a traditional for loop:
A = [3,4,5,6,2]
[A.pop(-1) for a in range(len(A))]
Output:
>>> A
[]
Here you are trying to iterate through the elements of a list while the length of the list is reduced by 1 for each iteration.
This is not the right way to do this,
Try this,
A = [3,4,5,6,2]
for _ in range(len(A)):
A.pop()
This will work.
Note: Never loop through a list in which you are going to perform some operations inside the loop-body. Try duplicating the list or use some other conditions.

For loop syntax in Python without using range() or xrange()

I do not know much about python so i apologize if my question is a very basic one.
Let's say i have a list
lst = [1,2,3,4,5,6,7,8,9,10]
Now what i want to know is that if there is any way to write the following piece of code in python without using range() or xrange():
for i in lst:
for j in lst after element i: '''This is the line i want the syntax for'''
#Do Something
The second loop is to access elements after the element i i.e., if i = 3, j would have to loop through from 4 to 10, so the pairs of numbers if i and j are printed would be (1,2)..(1,10), (2,3)...(2,10), (3,4)..(3,10) etc.
I have no idea what to search for or what query to type on any search engine.
Any help would be much appreciated.
This is what list slicing is about, you can take part of your list from i'th element through
lst[i:]
furthermore, in order to have both index and value you need enumerate operation, which changes the list into list of pairs (index, value)
thus
for ind, i in enumerate(lst):
for j in lst[ind+1: ]:
#Do Something
It looks like you might want to use enumerate():
for index, item in enumerate(lst):
for j in lst[index+1:]:
#Do Something

How does the enumerate function work?

I am supposed to do the following:
Define a function my_enumerate(items) that behaves in a similar way to the built-in enumerate function. It should return a list of pairs (i, item) where item is the ith item, with 0 origin, of the list items (see the examples below). Check the test cases for how the function should work. Your function must not call Python's in-built enumerate function.
Examples:
Input:
ans = my_enumerate([10, 20, 30])
print(ans)
Output:
[(0, 10), (1, 20), (2, 30)]
What does enumerate do? Try expressing it in English, and it may help you understand how to write the necessary code. If it doesn't then the practice of learning English language descriptions into code will be useful.
One way of describing enumerate is to say it iterates over each item in the list, and for each item in the input list it produces a pair of the item's index in the input list and the item.
So we know we need to iterate over the list:
for item in input_list:
pass
And we need to keep track of the index of the current item.:
index = 0
for item in input_list:
index += 1
Hmm, there's a better way of doing that:
for index in range(len(input_list)):
pass
Now to produce the pairs:
for index in range(len(input_list)):
pair = index, input_list[index]
You also need somewhere to store these pairs:
def my_enumerate(input_list):
output_list = []
for index in range(len(input_list)):
pair = index, input_list[index]
output_list.append(pair)
return output_list
Are there other ways to write code that produces the same output? Yes. Is this the best way to write this function? Not by a long shot. What this exercise should help you with is turning your thoughts into code, as you gain more experience doing that then you can combine multiple steps at a time, and start using more complicated programming concepts.
Use itertools.count and zip:
from itertools import count
def my_enumerate(values):
return list(zip(count(), values))

What does a for loop within a list do in Python?

Can someone explain the last line of this Python code snippet to me?
Cell is just another class. I don't understand how the for loop is being used to store Cell objects into the Column object.
class Column(object):
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.
The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
Explanation:
To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.
Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.
For instance:
myList = []
for i in range(10):
myList.append(i)
is equivalent to
myList = [i for i in range(10)]
List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.
This example only collects even numbered values in the list:
myList = []
for i in range(10):
if i%2 == 0: # could be written as "if not i%2" more tersely
myList.append(i)
and the equivalent list comprehension:
myList = [i for i in range(10) if i%2 == 0]
Two final notes:
You can have "nested" list comrehensions, but they quickly become hard to comprehend :)
List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.
Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:
data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]
gives:
new_data
[3.0, 7.4, 8.2]
It is the same as if you did this:
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
This is called a list comprehension.

Categories