Ryan
Ryan

Reputation: 129

issue with for loop in python only gets the last item

I'm a beginner in python, currently I'm trying to automate filling website field using selenium.

I'm trying to iterate over nested lists using for loop but always get only the last element. Any suggestions why?

fields = [['a','b','c'],['x','y','z']]
for i in range(len(fields)):
    driver.find_element_by_xpath("element").send_keys(fields[i][0],fields[i[1],fields[i][2])
    driver.find_element_by_xpath("element_save").click()

#then loop and iterate through 2nd nested list

# OUTPUT = x,y,z

I expect to iterate starting with index 0 to the end of the list.

Upvotes: 1

Views: 2383

Answers (2)

Archit Kithania
Archit Kithania

Reputation: 307

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.

Upvotes: 0

Max Voitko
Max Voitko

Reputation: 1629

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)

Upvotes: 3

Related Questions