简体   繁体   中英

Python Beginner - How do I recall the deleted items from a list

I am a python beginner and I was wondering once the item on the list is replaced, can it be recalled back?

Friends=["Jen","Lam","Sam","Song"]
print (Friends)

#replace a list item 
Friends[0] = "Ken"
print (Friends)

How should I write the line if I wanna say that Jen is replaced by Ken in python by not directly writing print("Jen") out and using a variable.

Keep track of Friends[0] before replacing it.

ie

friends=["Jen","Lam","Sam","Song"]
print(Friends)
replaced = friends[0]
friends[0] = "Ken"
print(replaced + " was replaced by " + friends[0])

You can also use pop and insert .

friends=["Jen","Lam","Sam","Song"]
print(friends)
replaced = friends.pop(0)
friends.insert(0, "Ken")
print(replaced + " was replaced by " + friends[0])

Not that I know of. But you could just make a copy of the list and use that to change it back to what it was by getting the old name from that list.

Friends=["Jen","Lam","Sam","Song"]
replaceName = Friends[0]
newName= "ken"
Friends [0] = newName

print(replaceName, " was replaced by ", newName)
print(Friends)

You would have to store "jen" as a variable if you wanted to replace the name with "ken" in the list. Something like this:

replace = Friends[0]
Friends[0] = "ken"

after these two lines, when you print(Friends[0]) it would return "Ken" but you could print(replace) and it would print "jen"

You can also utilize other list methods to .append Ken to the list to have both names in the list. This site is very helpful for all the different list methods and how to use them! https://docs.python.org/3.9/tutorial/datastructures.html#the-del-statement

Keep "Jen" in a separate variable.

I am also a beginner by the way :)

Friends = ["Jen", "Lam", "Sam", "Song"]

friend_to_delete = Friends[0]

print (Friends)

Friends[0] = "Ken"

print (Friends)

print(friend_to_delete, 'was replaced by', Friends[0])

Very simple answer:

    Friends=['Jen', 'Lam', 'Sam', 'Song']                                     
    print (Friends)
    Friends.append('Ken') #This adds in the string('Ken') without directly altering the list
    Friends.reverse() #This reverses the order in your list
    Friends.remove('Jen') #This removes the string ('Jen') from your list

#Note you can also use Friends.pop(4) to remove the string 'Jen' since its reversed
    
print(Friends)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM