Home > Back-end >  Appending values to a tuple
Appending values to a tuple

Time:05-20

This code appends a new value directly to a tuple. But, tuples are supposed to be nonchangeable. Could someone explain what is happening here?

word_frequency = [('hello', 1), ('my', 1), ('name', 2),
('is', 1), ('what', 1), ('?', 1)]

def frequency_to_words(word_frequency):
  frequency2words = {}
  for word, frequency in word_frequency:
    if frequency in frequency2words:
      frequency2words[frequency].append(word)
    else:
      frequency2words[frequency] = [word]
  return frequency2words

print(frequency_to_words(word_frequency))

Result: {1: ['hello', 'my', 'is', 'what', '?'], 2: ['name']}

CodePudding user response:

This line makes a list []

frequency2words[frequency] = [word]

That's what you are .append()'ing to.

But you can do (1,2) (3,4) and Python will make a bigger tuple to hold four things and copy them in, to make it look like it works. What you can't do is mutate the contents of a () tuple:

>>> t = (1,2)
>>> t[0] = 5
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    t[0] = t
TypeError: 'tuple' object does not support item assignment

CodePudding user response:

The .append() operation is done on the list values in the frequency2words dictionary, not the tuples in word_frequency.

You can rewrite your code to be more concise using .setdefault(), which should also make it more clear what you're appending to.

def frequency_to_words(word_frequency):
  frequency2words = {}
  for word, frequency in word_frequency:
      frequency2words.setdefault(frequency, []).append(word)
  return frequency2words
  • Related