Reputation: 23
I am trying to write a code that will basically ask the user to input 5 names. It will then create a list of those names, and print them out. Subsequently, it prints a sorted version of the list. Next, the code will print the third name in the list. After this step, the code asks the user which of the names to change whereupon the user then inputs a new name for the one they chose to replace.
This should be the output, example:
The names are: "Sal", "Jane", "Fred", "Bob", "Cole"
The sorted names are: "Bob", "Cole", "Fred", "Jane", "Sal"
The third name in the list is: "Fred"
(This will be the third name from the sorted list)
The names are: "Bob", "Joe", "Fred", "Jane", "Sal"
(Assuming the user chose to replace the second name.
So far this is what I have for code:
name_list = input ("Please list 5 names here:")
name_list = name_list.split()
name_list = [name_list]
print ("The names in your list are:", name_list)
print ("The sorted list is:", name_list)
print(name_list[2:3])
The issues I'm having are for one, I cant figure out why the sorted list isn't "sorting" correctly, and secondly, the last line should be printing out the third name, but prints []
instead.
Upvotes: 1
Views: 88
Reputation: 11
name_list=input("enter the list of names ")
name_list.sort()
print "sorted name list is ",name_list
print "Third name is ",name_list[2:3]
item= input("enter the name to be modified ")
print "position of the name to be modified is",name_list.index(item)
print("enter a name to modify "+item+ "!")
newname= input("name: ")
position=name_list.index(item)
name_list[position]=newname
name_list.sort()
print"modifified list is ",name_list
Upvotes: 1
Reputation: 3147
This should work.
name_list = input ("Please list 5 names here:")
name_list = name_list.split()
print ("The names in your list are:", name_list)
print ("The sorted list is:", name_list.sort()) #sorting list
print(name_list[2]) # printing 3rd element of the list as indices start from 0
To find the index of element to be replaced (say "Fred") you can do:
index_to_be_replaced = name_list.index("Fred")
Once you find the index just execute :
name_list[index_to_be_replaced] = new_element to be inserted
Upvotes: 0
Reputation:
First of all you are not sorting the list before printing out the sorted list , you should call name_list.sort()
before printing sorted list.
Secondly , name_list[<start>:<end>]
prints out the list starting at <start>
index , and ending at <end> - 1
index , hence you are getting the empty list for name_list[2:3]
. You should do name_list[2]
instead.
Upvotes: 3
Reputation: 311188
It isn't sorting because you haven't sorted it, you've just placed it inside another list. Just call name_list.sort()
instead.
The slicing [2:3]
isn't working because after calling name_list = [name_list]
it's a list with a single element, which is itself a list of names. This list does not have an element in index 2, and hence an empty list is returned when you slice it like that.
Upvotes: 2