Another thing which I noticed is that some of my tags and categories have the same ID
Example:
I have a category named “Internet” as well as a tag named “Internet”. Both are having the ID 3.
Before running your code, I deleted the “Internet” tag and created a new tag with the same name but a different URL ( e.g Internet-tips). This time the tag ID was 557. If I ever create a new tag and name the slug as “Internet”, the ID becomes 3 which is equal to the ID of the “Internet” category.
I hope my explanation is not confusing.