my_list = [1, 2, 3, "hello", "rice", "code", 1.2]
count = 0
for i in my_list:
count += 1
The append() function adds a new item to the end of your list. A good use of this is to add an item to your list after your code fulfills a certain condition. Here's a simple example:
my_list = [1, 2, 3, "hello", "rice", "code", 1.2]
question = input("Do you love Python?: ").lower()
if question == "yes":
my_list.append("Python is the best!!") # use of the append() function
else:
my_list.append("You should try Python") # use of the append() function
print(my_list)
This example uses an if statement to add a certain sentence to the initial list based on the user's input.
The append() function can add only one item at a time to your list. Instead of the append function, you can use an operator instead:
my_list = [1, 2, 3, "hello", "rice", "code", 1.2]
my_list += ["Python is the best!!"]
Using the addition operator will ultimately be less efficient because it doesn't modify your initial list. Instead, it creates a new list in memory and adds a new item to it. The append() function modifies your initial list directly.
3) The extend() Function
The extend() function is a built-in function that adds several items to an existing list at once. It takes in the new items as an argument and modifies your existing list with the argument. Here's how to use the extend() function:
my_list.extend(["item", "muo", 350])
print(my_list)
# prints [1, 2, 3, 'hello', 'rice', 'code', 1.2, 'item', 'muo', 350]
The extend() function can only take one argument, so you should add all your items to a list like the code above.
4. The reverse() Function
The reverse function simply rewrites your list in the reverse order. Here's an example of the reverse function in use:
my_list = [1, 2, 3, "hello", "rice", "code"]
my_list.reverse()
print(my_list) # prints ['code', 'rice', 'hello', 3, 2, 1]
To reverse a list without using the reverse() function, you would need to slice your list. Here's an example:
my_list = [1, 2, 3, "hello", "rice", "code"]
reversed_list = my_list[::-1]
print(reversed_list) # prints ['code', 'rice', 'hello', 3, 2, 1]
In the above example, my_list[::-1] creates a reversed copy of the original list. This means you'll have two lists in memory, which is not the best approach if you simply want to reverse the original list.
JJJJJJJ
No comments:
Post a Comment