0

When I run the following code, I get the output below, which is correct:

for object in buck:
    if object.url.startswith("https://....01fhekh01") \
    or object.url.startswith("https://...01fkejrig05"):
        print(object)

Output:

<Object url='https://....01fhekh01-fkjflekjl' etag='"ewjhwehroie30923r"'>
<Object url='https://.......01fkejrig05-fjkjefojeof' etag='"265af8a7a0b69d3c173d40916fc2c5eb"'>

However, when I print my output outside of the loop statement, I get a different output, which is wrong:

for object in buck:
    if object.url.startswith("https://....01fhekh01") \
    or object.url.startswith("https://...01fkejrig05"):
        print(object)

print(object)

Output:

*correct output from the print inside the loop statement*

wrong output from the print outside of the loop statement:
<Object url='https://....kjwekjweijtoeirjtoeri' etag='"sfakjlakfjsf"'>

How can I print the correct output out of the loop statement?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Broc
  • 39
  • 1
  • 4
  • 2
    you are changing the value of object in each iteration of hte loop. When you print object outside the loop it will just be the last value that object was set to on the last iteration – Chris Doyle Jan 18 '21 at 17:45
  • 1
    I don't understand what you are asking. If the first code does what you want and the second doesn't, the answer is "use the first code". – mkrieger1 Jan 18 '21 at 17:45
  • The real answer is probably to transform your loop into a function that ``return``s the first match or ``yield``s all of them, but it is not really possible to tell without knowing what you actually intend to achieve. – MisterMiyagi Jan 18 '21 at 17:47

1 Answers1

2

hi you can try this :

 ls=[]
 for object in buck:
    if object.url.startswith("https://....01fhekh01") \
    or object.url.startswith("https://...01fkejrig05"):
       ls.append(object)
print(ls)