tags:

views:

295

answers:

5

I'm following a couple of Pythone exercises and I'm stumped at this one.

# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
  # +++your code here+++
  return

What is a Tuple? Do they mean a List of Lists?

+12  A: 

The tuple is the simplest of Python's sequence types. You can think about it as an immutable (read-only) list:

>>> t = (1, 2, 3)
>>> print t[0]
1
>>> t[0] = 2
TypeError: tuple object does not support item assignment

Tuples can be turned into new lists by just passing them to list() (like any iterable), and any iterable can be turned into a new tuple by passing it to tuple():

>>> list(t)
[1, 2, 3]
>>> tuple(["hello", []])
("hello", [])

Hope this helps. Also see what the tutorial has to say about tuples.

AKX
+2  A: 

A tuple and a list is very similar. The main difference (as a user) is that a tuple is immutable (can't be modified)

In your example:

[(2, 2), (1, 3), (3, 4, 5), (1, 7)]

This is a list of tuples [...] is the list (2,2) is a tuple

Kim
+10  A: 
J.F. Sebastian
answer to the exercise (not related to tuples): `import operator; tuples.sort(key=operator.itemgetter(1))`
J.F. Sebastian
A: 

Tuples are used to group related variables together. It's often more convenient to use a tuple rather than writing yet another single-use class. Granted, accessing their content by index is more obscure than a named member variable, but it's always possible to use 'tuple unpacking':

def returnTuple(a, b):
    return (a, b)

a, b = returnTuple(1, 2)
Pieter Witvoet
+1  A: 

The best summary of the differences between lists and tuples I have read is this:

One common summary of these more interesting, if subtle, differences is that tuples are heterogeneous and lists are homogeneous. In other words: Tuples (generally) are sequences of different kinds of stuff, and you deal with the tuple as a coherent unit. Lists (generally) are sequences of the same kind of stuff, and you deal with the items individually.

From: http://news.e-scribe.com/397

Goyuix
In Haskell, list items must be same Type, while tuple is not. But this is not true in Python. In Python, the difference is immutability.
weakish