What are “named tuples” in Python?

Named tuples are basically easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax. They can be used similarly to struct or other common record types, except that they are immutable. They were added in Python 2.6 and Python 3.0, although there is a recipe for … Read more

How do I expand a tuple into variadic template function’s arguments?

In C++17 you can do this: std::apply(the_function, the_tuple); This already works in Clang++ 3.9, using std::experimental::apply. Responding to the comment saying that this won’t work if the_function is templated, the following is a work-around: #include <tuple> template <typename T, typename U> void my_func(T &&t, U &&u) {} int main(int argc, char *argv[argc]) { std::tuple<int, float> … Read more

Sort a list of tuples by 2nd item (integer value) [duplicate]

Try using the key keyword with sorted(). sorted([(‘abc’, 121),(‘abc’, 231),(‘abc’, 148), (‘abc’,221)], key=lambda x: x[1]) key should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1]. For optimization, see jamylak’s response using itemgetter(1), which … Read more

What’s the difference between lists and tuples?

Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order. Using this distinction makes code more explicit and understandable. One example would be pairs of page and … Read more