Issue #26494: Fixed crash on iterating exhausting iterators.
Affected classes are generic sequence iterators, iterators of bytearray,
list, tuple, set, frozenset, dict, OrderedDict and corresponding views.
diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c
index 1fdd916..edb67a4 100644
--- a/Objects/bytearrayobject.c
+++ b/Objects/bytearrayobject.c
@@ -2982,8 +2982,8 @@
         return item;
     }
 
-    Py_DECREF(seq);
     it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }
 
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index fe19356..e3e4765 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -2586,8 +2586,8 @@
     return key;
 
 fail:
-    Py_DECREF(d);
     di->di_dict = NULL;
+    Py_DECREF(d);
     return NULL;
 }
 
@@ -2658,8 +2658,8 @@
     return value;
 
 fail:
-    Py_DECREF(d);
     di->di_dict = NULL;
+    Py_DECREF(d);
     return NULL;
 }
 
@@ -2744,8 +2744,8 @@
     return result;
 
 fail:
-    Py_DECREF(d);
     di->di_dict = NULL;
+    Py_DECREF(d);
     return NULL;
 }
 
diff --git a/Objects/iterobject.c b/Objects/iterobject.c
index 9c90abe..346d2d9 100644
--- a/Objects/iterobject.c
+++ b/Objects/iterobject.c
@@ -69,8 +69,8 @@
         PyErr_ExceptionMatches(PyExc_StopIteration))
     {
         PyErr_Clear();
-        Py_DECREF(seq);
         it->it_seq = NULL;
+        Py_DECREF(seq);
     }
     return NULL;
 }
diff --git a/Objects/listobject.c b/Objects/listobject.c
index 27365b6..c414620 100644
--- a/Objects/listobject.c
+++ b/Objects/listobject.c
@@ -2915,8 +2915,8 @@
         return item;
     }
 
-    Py_DECREF(seq);
     it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }
 
@@ -3018,9 +3018,17 @@
 listreviter_next(listreviterobject *it)
 {
     PyObject *item;
-    Py_ssize_t index = it->it_index;
-    PyListObject *seq = it->it_seq;
+    Py_ssize_t index;
+    PyListObject *seq;
 
+    assert(it != NULL);
+    seq = it->it_seq;
+    if (seq == NULL) {
+        return NULL;
+    }
+    assert(PyList_Check(seq));
+
+    index = it->it_index;
     if (index>=0 && index < PyList_GET_SIZE(seq)) {
         item = PyList_GET_ITEM(seq, index);
         it->it_index--;
@@ -3028,10 +3036,8 @@
         return item;
     }
     it->it_index = -1;
-    if (seq != NULL) {
-        it->it_seq = NULL;
-        Py_DECREF(seq);
-    }
+    it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }
 
diff --git a/Objects/setobject.c b/Objects/setobject.c
index 18e6898..3958a6c 100644
--- a/Objects/setobject.c
+++ b/Objects/setobject.c
@@ -871,8 +871,8 @@
     return key;
 
 fail:
-    Py_DECREF(so);
     si->si_set = NULL;
+    Py_DECREF(so);
     return NULL;
 }
 
diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c
index 5d72806..550719f 100644
--- a/Objects/tupleobject.c
+++ b/Objects/tupleobject.c
@@ -966,8 +966,8 @@
         return item;
     }
 
-    Py_DECREF(seq);
     it->it_seq = NULL;
+    Py_DECREF(seq);
     return NULL;
 }