0

There is a list filled with tuples, like

pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')]  

How do I find the length of, like, first tuple? len(pairs) returns me 3 and len(pairs[]) returns error. How do I get the length of a tuple inside the list?

user127161
  • 41
  • 1
  • 1
  • 5
  • 4
    Just access it: `len(pais[0])`... – Paulo Bu Jul 06 '14 at 18:54
  • That's not an `array`, that's a `list`. – Matthias Jul 06 '14 at 18:56
  • 1
    @Matthias while you are correct thats just a minor quibble and semantics ... a list in python is roughly equivalent to an array in python with the exception that arrays can only hold very specific data types ... and is roughly analogous to an array in any other language – Joran Beasley Jul 06 '14 at 19:03
  • Any other language? Basic, C, C#, C++, Clojure, Pascal (and Delphi), Haskell, Io, Java, Rust, Scheme and Smalltalk don't call lists an array. – Matthias Jul 07 '14 at 07:06

1 Answers1

3

len(pairs[]) raises a SyntaxError because the square brackets are empty:

>>> pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')]
>>> pairs[]
  File "<stdin>", line 1
    pairs[]
          ^
SyntaxError: invalid syntax
>>>

You need to tell Python where to index the list pairs:

>>> pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')]
>>> pairs[0]  # Remember that Python indexing starts at 0
('cheese', 'queso')
>>> pairs[1]
('red', 'rojo')
>>> pairs[2]
('school', 'escuela')
>>> len(pairs[0])  # Length of tuple at index 0
2
>>> len(pairs[1])  # Length of tuple at index 1
2
>>> len(pairs[2])  # Length of tuple at index 2
2
>>>

I think it would be beneficial for you to read An Introduction to Python Lists and Explain Python's slice notation.

Community
  • 1
  • 1