# Algorithms

## Останній елемент в переборі

Часто є необхідність обробляти якийсь масив/список і при досягненні останнього елементу зробити щось не так, як з усіма попередніми, наприклад, замість коми поставити крапку, або заміть повідомлення "Press any key..." просто завершити програму.

```python
domains = ['dom1', 'dom2', 'dom3', 'dom4']  # список доменів для обробки
not_last = len(domains)      # довжину списку в змінну "не останній"
comma_list = ''              # змінна для перевірки

for dom in domains:          # у переборі...
    not_last -= 1            # ...зі змінної "не останній" віднімаємо 1
    comma_list += dom        # щось там робимо з доменом...

    if not_last:             # якщо це "не останній", то...
        comma_list += ', '   # ...додаємо кому
        print(comma_list)
        print('Press any key to continue...')
    else:                    # якщо останній, то...
        comma_list += '.'    # ...ставимо крапку
        print(comma_list)

```

```
dom1, 
Press any key to continue...
dom1, dom2, 
Press any key to continue...
dom1, dom2, dom3, 
Press any key to continue...
dom1, dom2, dom3, dom4.
```

Правда, якщо стоїть реальна задача "розділити комами і поставити крапку", то це можна вирішити більш елегантно:

```python
domains = ['dom1', 'dom2', 'dom3', 'dom4']
new_comma_list = ', '.join(domains) + '.'

print(f'{new_comma_list=}')
```

```
new_comma_list='dom1, dom2, dom3, dom4.'
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://olexsyn.gitbook.io/enote/progr/python/algorithms.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
