Prevent infinite loop when reaching end of list