Reputation: 19
I don't understand what I am doing wrong. The output I receive from this code is not right.
Modify short_names by deleting the first element and changing the last element to Joe. Sample output from given program: ['Sam', 'Ann', 'Joe']
short_names = ['Gertrude', 'Sam', 'Ann', 'Joseph']
"Your solution here"
print(short_names)
My code:
short_names = ['Gertrude', 'Sam', 'Ann', 'Joseph']
short_names.pop()
short_names.sort()
print(short_names)
Upvotes: 1
Views: 26135
Reputation: 412
The Python del keyword is used to delete objects.Here, object can be variables, user-defined objects, lists, items within lists, dictionaries etc.
short_names = ['Gertrude', 'Sam', 'Ann', 'Joseph']
del short_names[0] #del will delete the object of short_names[0]
Copying short_names[1:] values from index 1 to last into a new reference variable short_names that means leaving 0 index value.
short_names=short_names[1:]
Lambda function copy values from 1 index to last index and return the list
short_=lambda x:x[1:]
print(short_(short_names))
Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.
short_names.pop(0)#if index is not specified it will return last element
To update list
using negative index
short_names[-1]='jeo'
using positive indexing , find the length of string and reduce 1 from it because index are 0 based.
short_names[len(short_names)-1]='jeo'
delete the last element and then insert new element
short_names.pop()
short_names.append('jeo')
#or short_names.insert(index,value)
Upvotes: 0
Reputation: 21
This code worked for me:
user_input = input()
short_names = user_input.split()
del short_names[0]
short_names[2] = 'Joe'
print(short_names)
Upvotes: -1
Reputation: 1
user_input = input()
short_names = user_input.split()
del short_names[0] # delete the first element
short_names[2] = "Joe" # change the last element to Joe
print(short_names)
Upvotes: -1
Reputation: 932
Another way:
short_names = ['Gertrude', 'Sam', 'Ann', 'Joseph']
short_names[-1] = 'Joe'
short_names = short_names[1:len(short_names)]
print(short_names)
Upvotes: 0
Reputation: 33754
You want to pop at index 0 (the first item). Without specifying the index, the default is the last index.
short_names.pop(0)
And to modify the last item, just modify the list at index -1.
short_names[-1] = "Joe"
Upvotes: 3