Java: Get first item from a collection

Looks like that is the best way to do it: String first = strs.iterator().next(); Great question… At first, it seems like an oversight for the Collection interface. Note that “first” won’t always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn’t … Read more

Why do I get “TypeError: ‘int’ object is not iterable” when trying to sum digits of a number? [duplicate]

Your problem is with this line: number4 = list(cow[n]) It tries to take cow[n], which returns an integer, and make it a list. This doesn’t work, as demonstrated below: >>> a = 1 >>> list(a) Traceback (most recent call last): File “<stdin>”, line 1, in <module> TypeError: ‘int’ object is not iterable >>> Perhaps you … Read more

Check if a variable type is iterable?

You may create a trait for that: namespace detail { // To allow ADL with custom begin/end using std::begin; using std::end; template <typename T> auto is_iterable_impl(int) -> decltype ( begin(std::declval<T&>()) != end(std::declval<T&>()), // begin/end and operator != void(), // Handle evil operator , ++std::declval<decltype(begin(std::declval<T&>()))&>(), // operator ++ void(*begin(std::declval<T&>())), // operator* std::true_type{}); template <typename T> std::false_type … Read more