Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to append a more values to a tuple

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']}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading