💡 Python Lists: Adding and Extending
Use
Code explanation: The code first initializes a list.
#Python #PythonLists #DataStructures #CodingTips #PythonCheatsheet
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Use
.append() to add a single item to the end of a list. Use .extend() to add all items from an iterable (like another list) to the end.# Create a list of numbers
my_list = [10, 20, 30]
# Add a single element
my_list.append(40)
# my_list is now [10, 20, 30, 40]
print(f"After append: {my_list}")
# Add elements from another list
another_list = [50, 60]
my_list.extend(another_list)
# my_list is now [10, 20, 30, 40, 50, 60]
print(f"After extend: {my_list}")
Code explanation: The code first initializes a list.
.append(40) adds the integer 40 to the end. Then, .extend() takes each item from another_list and adds them individually to the end of my_list.#Python #PythonLists #DataStructures #CodingTips #PythonCheatsheet
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨