Oct-19-2018, 08:42 PM
Hello,
I recently started with learning Python and don't fully understand how a nested loop works.
Below I have 2 similar codes with the only difference that I create in the first code an empty list 'int_fields' before the loop and in the second code I put an empty list 'int fields' within the loop.
I see the difference in output, but I don't know how the double loop causes the difference in output. Could somebody please give some clarification?
I recently started with learning Python and don't fully understand how a nested loop works.
Below I have 2 similar codes with the only difference that I create in the first code an empty list 'int_fields' before the loop and in the second code I put an empty list 'int fields' within the loop.
I see the difference in output, but I don't know how the double loop causes the difference in output. Could somebody please give some clarification?
string_list = ['1994,1,1,6,8096', '1994,1,2,7,7772', '1994,1,3,1,10142'] final_list = [] int_fields = [] for data in string_list: string_fields = data.split(",") for value in string_fields: intvalue = int(value) int_fields.append(intvalue) final_list.append(int_fields) print(final_list)
Output:[[1994, 1, 1, 6, 8096, 1994, 1, 2, 7, 7772, 1994, 1, 3, 1, 10142],
[1994, 1, 1, 6, 8096, 1994, 1, 2, 7, 7772, 1994, 1, 3, 1, 10142],
[1994, 1, 1, 6, 8096, 1994, 1, 2, 7, 7772, 1994, 1, 3, 1, 10142]]
string_list = ['1994,1,1,6,8096', '1994,1,2,7,7772', '1994,1,3,1,10142'] final_list = [] for data in string_list: int_fields = [] string_fields = data.split(",") for value in string_fields: intvalue = int(value) int_fields.append(intvalue) final_list.append(int_fields) final_list
Output:[[1994, 1, 1, 6, 8096], [1994, 1, 2, 7, 7772], [1994, 1, 3, 1, 10142]]
Thanks,