Detailed Explanation of Knowledge Points of python Slice Copy List

  • 2021-12-05 06:30:38
  • OfStack

1. Do not specify the starting and ending indexes [:], so that the resulting slice can contain the whole list, and then give the slice a new variable, thus realizing copying the list.

2. Create a copy of the original list, and the operation of the two lists will not affect.

Instances


names = ["Jerry", "Tom"]
names_copy = names[:]
names.append("Ann")
names_copy.append("Bob")
print(f"names : {names}")
print(f"names_copy : {names_copy}")
# output:
# names : ['Jerry', 'Tom', 'Ann']
# names_copy : ['Jerry', 'Tom', 'Bob']

List Slicing Code Sample for Python Study Notes


""" Slice """
pepole = ["koulong","liding","ceshi","xiaohong"]
print(pepole[0:1])
print(pepole[:2])
print(pepole[-1:])

# Access slices of all elements 
for people in pepole[0:1]:
    print(people.title())

# Copy slicing 
my_foods = [" Bananas "," Apple "," Pear "]
my_friend_foods = my_foods[0:2]
print(" My favorite fruit: " + str(my_foods))
print(" My favorite fruits are: ")
for my_foods1 in my_foods:
    print(my_foods1)
print(" My friend's favorite fruit: " + str(my_friend_foods))
print(" My friend's favorite fruits are ")
for my_friend_foods1 in my_friend_foods:
    print(my_friend_foods1)
my_friend_foods.append(" Grapes ")
print(" My friend's favorite fruit: " + str(my_friend_foods))
my_friend_foods2 = my_friend_foods.remove(" Grapes ")
my_friend_foods.append(" Watermelon ")
print(my_friend_foods)
# Practice with hands 1 Practice 
my_foods.append(" Mango ")
print(" My favorite former 2 Fruits: " + str(my_foods[0:2]))
print(my_foods)
print(" My favorite 4 The middle of a fruit 2 Fruits: " + str(my_foods[1:3]))
print(" My favorite last 3 Fruits: " + str(my_foods[1:4]))

Related articles: