Search code examples
pythonlisttuples

Python tuple inside list


I have a data structure like below, How do I append new values based on the name. Like, if input name is Sam and amount is 200. if Sam already existed, it should append to Sam's list otherwise it should create a new element in the list.

data = [('Sam',[100,120,110]),('Andrew',[80,90,100]),('Gram',[400,300,350]),
              ('Jeremy',[125, 100]), ('Mike',[75,30])]

Solution

  • Iterating over list of tuples and replace / add tuple

    As a basic rule, tuples are non-mutable. So you cannot change a tuple. However, you can replace a tuple with another tuple inside a list. That's how we are going to solve your problem.

    Here's the code to do this.

    data = [('Sam',[100,120,110]),('Andrew',[80,90,100]),('Gram',[400,300,350]),
                  ('Jeremy',[125, 100]), ('Mike',[75,30])]
    
    name = input ('Enter name to add to list : ')
    while True:
        try:
            value = int (input ('Enter value to add to list : '))
            break
        except:
            print ('not a number')
    
    for i,(nm,vals) in enumerate(data):
        if nm == name:
            vals +=[value]
            data[i] = (nm,vals)
            break
    else:
        data.append ((name,[value]))
    
    print (data)
    

    The output is as follows: Example with a name that exists in the list:

    Enter name to add to list : Sam
    Enter value to add to list : 250
    [('Sam', [100, 120, 110, 250]), ('Andrew', [80, 90, 100]), ('Gram', [400, 300, 350]), ('Jeremy', [125, 100]), ('Mike', [75, 30])]
    

    Another example with a name that does not exist in the list:

    Enter name to add to list : Joe
    Enter value to add to list : 250
    [('Sam', [100, 120, 110]), ('Andrew', [80, 90, 100]), ('Gram', [400, 300, 350]), ('Jeremy', [125, 100]), ('Mike', [75, 30]), ('Joe', [250])]
    

    Using Dictionary instead of tuples

    If you are interested in an alternate approach, you can convert the list of tuples into a dictionary. Then insert the data into a dictionary, and convert it back to a list of tuple.

    #convert the list of tuples to a dict of lists 
    data_dict = {nm:vals for nm,vals in data}
    
    #use setdefault to add the value. append() allows you to append if key exists
    data_dict.setdefault(name,[]).append(value)
    
    #convert it back to a list of tuples
    data_list = [(nm,vals) for nm,vals in data_dict.items()]
    
    print (data_list)
    

    Same results as above.