Home > Enterprise >  inserting new values in a list position required both from the keyboard
inserting new values in a list position required both from the keyboard

Time:06-07

I am trying (python) to require from the keyboard a position of a list where later in that position I should add a name and salary also required from the keyboard

I tried the next sentence but it is not working. It is just showing the same values that I already have in the list

Could you help me?

Thanks

list1=[('pedro', [333]), ('juan', [9999])]

new=int(input('give me the position'))
name_new=input('give me the name')
salary_new=int(input('give me the salary'))

for i in range(len(list1)):
    if(i==new):
        list1[i].append([name_new,[salary_new]])

print(list1)

CodePudding user response:

I think you're trying to insert something in a list? if so you can use something like :

list1=[('pedro', [333]), ('juan', [9999])]

new=int(input('give me the position'))
name_new=input('give me the name')
salary_new=int(input('give me the salary'))

for i in range(len(list1)):
    if(i==new):
        list1.insert(i,[name_new,[salary_new]])

print(list1)

You probably want a dictionary to do what you expect instead of a list https://www.w3schools.com/python/python_dictionaries.asp

dict1= {'pedro':333, 'juan':9999}

new=int(input('give me the position'))
name_new=input('give me the name')
salary_new=int(input('give me the salary'))

if not name_new in dict1:
    dict1[name_new] = salary_new

print(dict1)

CodePudding user response:

Tuple without append, change the element instead

list1 = [('pedro', [333]), ('juan', [9999])]

new = int(input('give me the position'))
name_new = input('give me the name')
salary_new = int(input('give me the salary'))

for index, value in enumerate(list1):
    if index == new:
        list1[index] = (name_new, [salary_new])

print(list1)

  • Related