Python_4
Python_4
Today, you'll learn about two of Python's fundamental data structures: lists and tuples. These
structures allow you to store collections of items, each with their own properties and uses. Follow
the detailed plan below, complete the examples, and work through the exercises.
What is a List?
• Definition:
A list is an ordered, mutable (changeable) collection of items. Lists can hold items of any
data type, including numbers, strings, and even other lists.
• Creating a List:
You can create a list by placing items within square brackets [], separated by commas.
print(fruits)
2. Slicing:
Extract a portion of the list.
3. Adding Elements:
Use the .append() method to add an element at the end.
fruits.append("orange")
4. Inserting Elements:
Insert an element at a specified position with .insert(index, element).
fruits.insert(1, "mango")
5. Removing Elements:
Remove an element by value with .remove(), or by index using del or .pop().
last_fruit = fruits.pop()
print("Fruit:", fruit)
What is a Tuple?
• Definition:
A tuple is similar to a list in that it is an ordered collection of items. However, tuples are
immutable (their elements cannot be changed after creation).
• Creating a Tuple:
Tuples are created by placing items within parentheses (), separated by commas.
print(colors)
• Immutability:
Once created, you cannot modify a tuple. This is useful when you want to ensure the data
remains constant.
• Accessing Elements:
Like lists, tuples support indexing and slicing.
2. Steps:
Sample Code:
movies.append("The Prestige")
movies.remove("Interstellar")
2. Steps:
Sample Code:
python
numbers = [1, 2, 3, 4, 5]
print("Numbers:", numbers)
numbers.append(6)
exit()
Step 5: Additional Learning Resources