Alexander Caskie
Alexander Caskie

Reputation: 357

Appending a string to a list using a for loop where each item is appended is a new string

I am trying to create a new create a list where a new item is appended to the list through each iteration of a for loop. The code so far looks like such:

path_start = 'https://promo.betfair.com/betfairsp/prices/dwbfpricesukwin'
file = ".csv"

start = datetime.datetime.strptime("10-02-2007", "%d-%m-%Y")
end = datetime.datetime.strptime("21-02-2019", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

date_list = []

for date in date_generated:
    date_string = date.strftime("%d%m%Y")
    for path_name in date_string:
        x = path_start + date_string + file
        date_list.append(x)

print(date_list)

When I do this a list is created but each item in the list is identical. I want each item to use the date_string variable created in the previous for loop which should change in each iteration. This is an example of the list it creates:

['https://promo.betfair.com/betfairsp/prices/dwbfpricesukwin10022007.csv', 'https://promo.betfair.com/betfairsp/prices/dwbfpricesukwin10022007.csv'

I have tried changing the indentation of the loops but this did not solve the problem.

I also tried to increase the efficiency using numpy array but the answer to this question (How to declare and add items to an array in Python?) said to use a list. Since the list is particularly long any help to increase efficiency would also be appreciated.

Cheers, Sandy

Upvotes: 0

Views: 780

Answers (2)

lennhv
lennhv

Reputation: 103

you only need change the for loop like this:

date_list = []
for date in date_generated:
    date_list.append(path_start + date.strftime("%Y%m%d") + file)

print(date_list)

output example:

[...'https://promo.betfair.com/betfairsp/prices/dwbfpricesukwin20190124.csv',... 'https://promo.betfair.com/betfairsp/prices/dwbfpricesukwin20190219.csv'...]

NOTE: The second loop is not necessary because you no need loop over the date_string, you need apend the date to the string name

Upvotes: 1

aghast
aghast

Reputation: 15310

Your problem lies here:

for path_name in date_string:

The date_string is a string value at this point. Your path_name variable, which is not used inside the loop, is iterating character-by-character through the string.

This means you will have 8 values (ddmmyyyy= 8 chars) for each entry. If you look at every eighth entry in the resulting list, you will probably see changes.

I don't think you need the inner loop at all. Try just this:

for date in date_generated:
    date_string = date.strftime("%d%m%Y")
    x = path_start + date_string + file
    date_list.append(x)

Upvotes: 2

Related Questions