In the for loop, you're overwriting data at every iteration with data = coords_data. If data is a list, then use data.append(coords_data) instead to add new data to it at each iteration. Note that you'll need to initialize it before the for loop with data = []

Essentially:

data = []
for grp_str in group_strings:
   data.append(self.point_dict[grp_str]['Coords'])
Answer from glhr on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › why is my loop only iterating once?
r/learnpython on Reddit: Why is my loop only iterating once?
March 11, 2022 -

I positioned the return outside of the for loop as well but the same results.

def user(number, email, account_type):
    for i in range(number):
        f_name = fake.first_name()
        l_name = fake.last_name()
        email = "testmail.com"
        acct_type = account_type
        return f_name, l_name, acct_type, email
🌐
Reddit
reddit.com › r/learnpython › (pandas) for loop only recording final iteration
r/learnpython on Reddit: (Pandas) For loop only recording final iteration
June 24, 2021 -

Obligatory warning - new to Python and Pandas.

I'm having some difficulty executing a for loop. It is only returning the last value in the list.

I have a .csv file containing information that I'd like to run through CanvasAPI to post user scores. The .csv layout is:

Name user_id Score
0 Name_0 7454 90.0
1 Name_1 7075 96.0
2 Name_2 7377 76.0
3 Name_3 7259 49.0
4 Name_4 7294 48.0
5 Name_5 7491 76.5

My code for executing the loop is:

canvas = Canvas(API_URL, API_KEY)

#this gives access to a particular course
course = canvas.get_course(9997)

#this gives access to an assignment within the course
assignment = course.get_assignment(78290)

#this identifies users within that course, based on values in the dataframe/csv
userlist = [canvas.get_user(user) for user in df['user_id']]


length1 = len(userlist)

    #looping attempt2
    for i in range(length1):
        (userlist[i])
    
scorelist = df['Score']

length2 = len(scorelist)

    #looping attempt2
    for x in range(length2):
        (scorelist[x])

#this object selects specific submissions by users
submission = assignment.get_submission(userlist[i])
#this command posts grades 
submission.edit(submission={'posted_grade': scorelist[x]})

The loops successfully runs, but only the final row of the .csv is actually scored (for Name_5). What am I missing? Any help greatly appreciated.

Top answer
1 of 5
2

Because you're overwriting word in the loop, not really a good idea. You can try something like:

wordlist = ""
for word in wordStr:
    wordlist = "%s %s"%(wordlist,word.strip())
print wordlist[1:]

This is fairly primitive Python and I'm sure there's a more Pythonic way to do it with list comprehensions and all that new-fangled stuff :-) but I usually prefer readability where possible.

What this does is to maintain a list of the words in a separate string and then add each stripped word to the end of that list. The [1:] at the end is simply to get rid of the initial space that was added when the first word was tacked on to the end of the empty word list.

It will suffer eventually as the word count becomes substantial since tacking things on to the end of a string is less optimal than other data structures. However, even up to 10,000 words (with the print removed), it's still well under a second of execution time.

At 50,000 words it becomes noticeable, taking 3 seconds on my box. If you're going to be processing that sort of quantity, you would probably opt for a real list-based solution like (equivalent to above but with a different underlying data structure):

wordlist = []
for word in wordStr:
    wordlist.append (word.strip())
print wordlist

That takes about 0.22 seconds (without the print) to do my entire dictionary file, some 110,000 words.

2 of 5
1

To print all the words in wordStr (assuming that wordStr is some kind of iterable that returning strings), you can simply write

for word in wordStr:
    word = word.strip()
    print word # Notice that the only difference is the indentation on this line

Python cares about indentation, so in your code the print statement is outside the loop and is only executed once. In the modified version, the print statement is inside the loop and is executed once per word.

Top answer
1 of 2
3

You don't need range(len(list_)) for iterating over indeces only.

Usual for will do. You can also unpack list with *:

fields = [['a','b','c'],['x','y','z']]
len_ = len(fields)
for i in range(len_):
    driver.find_element_by_xpath("element").send_keys(*fields[i])

You could also iterate trhrough the values of the fields itself:

fields = [['a','b','c'],['x','y','z']]

for field in fields:
    driver.find_element_by_xpath("element").send_keys(*field)
2 of 2
0

Firstly there is a bug in your program as you have written it:

fields = [['a','b','c'],['x','y','z']]
for i, v in enumerate(fields):
    driver.find_element_by_xpath("element").send_keys(fields[i][0],fields[i[1],fields[i][2])
                                                                           ^ # No closing ]

Secondly there is a term that Python developers like to throw around: Pythonic Code.

We like to write short concise code that favors readability over squeezing every last inch of performance.

Referring to this you should change your code as it is unnecessarily cluttered and you are not even utilizing the value element of enumerate. I would recommend the following:

fields = [['a','b','c'],['x','y','z']]
for field in fields:
    name, age, height = field  # Replace this line with whatever the fields represent
    driver.find_element_by_xpath("element").send_keys(name, age, height)

This code is short, concise, and above all extremely readable to someone else.

Note: Replace the name, age, height with whatever they represent in your program.

If in fact this didn't solve your problem, your problem may not be with python but with selenium itself and that is out of the scope of this question. You can test this with simply printing the values before feeding it to the selenium function like this:

fields = [['a','b','c'],['x','y','z']]
for field in fields:
    name, age, height = field  # Replace this line with whatever the fields represent
    print(name, age, height)
    driver.find_element_by_xpath("element").send_keys(name, age, height)

Hope this helps.

🌐
Stack Overflow
stackoverflow.com › questions › 28930597 › python-loop-only-printing-last-value
Python: Loop only printing last value - Stack Overflow
You don't need to use float values here; stick with int and use the % modulus (remainder) operator; this has the advantage you can then use a range() to produce all odd numbers up to N:
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 33106760 › for-loop-returning-the-last-object-not-the-preceding-ones-python
for loop returning the last object not the preceding ones python - Stack Overflow
But your outer loop still iterate only once, i can't really understand your code and use case, but you could use yield instead of return if you have generator concept and matches your use case. ... Sign up to request clarification or add additional context in comments. ... but now it returns the last 2 dictionaries i still want the function to return all of the dictionaries the code is reading a list of ids and what is being printed is what is in each folder for which the id is given ie: vendor_ids 2015-10-13T15:56:33.663Z+00:00
🌐
Quora
quora.com › How-do-I-get-rid-of-the-use-of-end-in-loops-Python-for-only-the-last-element
How to get rid of the use of “end” in loops (Python) for only the last element - Quora
You can’t use for-in loop to ... is only holding the value from your list and not directly pointing to that particular list item. So, you can modify item in any way you like without affecting the list. If you really want to use a for-in loop, you can use the built-in Python function enumerate() which will return a tuple consisting ...
🌐
Stack Overflow
stackoverflow.com › questions › 71354442 › for-loop-to-update-dictionary-is-only-returning-last-value
python - for loop to update dictionary is only returning last value - Stack Overflow
If you're referring to the print, it's because it's only printing the latest value stored in your variable parameters after the code finishes running the for loop. ... You completely overwrite your entire dictionary with parameters = {'website': ...
🌐
Stack Overflow
stackoverflow.com › questions › 48179486 › praw-for-loop-only-returning-last-value
python 3.x - PRAW for loop only returning last value - Stack Overflow
Indentation was your downfall. The reason your code was failing was because comments were only assigned after the sub_ids have finished looping. So when you iterate through comments, they're only the last sub_id's comments.
🌐
Stack Overflow
stackoverflow.com › questions › 58321364 › why-the-function-is-only-returning-the-last-value
python 3.x - Why the function is only returning the last value? - Stack Overflow
Art has a great concise single line solution to your problem. As he pointed out 'labels' is a single value that gets overwritten each time you cycle through your 'for' loop. You need to define a list for append() to work properly.