Working with Lists, Indexing, and Slicing in Python
In this lab, you will learn about lists, indexing, and slicing in Python. Lists are versatile data structures that allow you to store multiple items in a single variable. You can perform the exercises in any of the following environments:
- Visual Studio Code (VS Code)
- Google Colab
- Jupyter Notebook
- PyCharm
- Anaconda
Setup Instructions
1. Visual Studio Code (VS Code)
- Installation: Ensure Python is installed and the Python extension is added to VS Code.
- Create a New File: Open VS Code and create a new Python file (e.g.,
lists_lab.py
). - Run the Code: Use the editor’s terminal or run button to execute your code.
2. Google Colab
- Access Colab: Go to Google Colab.
- Create a New Notebook: Click on “New Notebook.”
- Run Cells: Write your code in a cell and run it by clicking the play button.
3. Jupyter Notebook
- Installation: Install Jupyter Notebook via Anaconda or Pip.
- Start Jupyter: Open your terminal and type
jupyter notebook
to launch. - Create a New Notebook: Create a new Python notebook and write your code in the cells.
4. PyCharm
- Installation: Download and install PyCharm.
- Create a New Project: Start a new project and create a new Python file.
- Run the Code: Write and run your code using the built-in run configuration.
5. Anaconda
- Launch Anaconda Navigator: Open Anaconda Navigator.
- Choose an Environment: Launch either Jupyter Notebook or Spyder.
- Create a New File/Notebook: Write your code in a new notebook or script.
Exercises
Exercise 1: Creating and Printing a List
Task:
- Create a list of your favorite fruits and print it.
Example Code:
# Create a list of favorite fruits
fruits = ["apple", "banana", "cherry", "date"]
# Print the list
print("Favorite Fruits:", fruits)
Exercise 2: Accessing Elements by Index
Task:
- Access and print the first and last elements of the list.
Example Code:
# Access and print the first and last elements
first_fruit = fruits[0]
last_fruit = fruits[-1]
print("First Fruit:", first_fruit)
print("Last Fruit:", last_fruit)
Exercise 3: Slicing a List
Task:
- Slice the list to get the second and third fruits and print them.
Example Code:
# Slice the list to get the second and third fruits
sliced_fruits = fruits[1:3]
print("Sliced Fruits:", sliced_fruits)
Exercise 4: Modifying a List
Task:
- Change the second fruit in the list and print the updated list.
Example Code:
# Change the second fruit
fruits[1] = "blueberry"
# Print the updated list
print("Updated Fruits:", fruits)
Exercise 5: Adding and Removing Elements
Task:
- Add a new fruit to the list and remove another fruit. Print the final list.
Example Code:
# Add a new fruit
fruits.append("elderberry")
# Remove a fruit
fruits.remove("date")
# Print the final list
print("Final Fruits List:", fruits)
Exercise 6: List Length and Iteration
Task:
- Print the length of the list and iterate through the list to print each fruit.
Example Code:
# Print the length of the list
print("Number of Fruits:", len(fruits))
# Iterate through the list and print each fruit
for fruit in fruits:
print("Fruit:", fruit)
Running the Code
- Copy the Code: Copy the code examples provided above into your Python file.
- Run the Program: Execute the program in your IDE. You can usually do this by clicking a “Run” button or using a keyboard shortcut (like
Shift + F10
in PyCharm). - Interact with the Program: Follow the prompts in the console to input your data if applicable.
Conclusion
This lab helps you understand how to work with lists in Python, including creating lists, indexing, slicing, modifying, and iterating them. By completing these exercises, you will gain practical experience in manipulating lists effectively.
Watch Vidio
or
Lab 08: Working with Lists, Indexing, and Slicing (Civil Engineering Focus)
Objective: Master list operations to manage engineering data like sensor readings, material properties, and structural loads.
Key Concepts
- Lists: Ordered collections of data (e.g., load values, soil layers).
- Indexing: Access individual elements (e.g.,
loads[0]
for the first load). - Slicing: Extract sublists (e.g.,
sensor_data[10:20]
for readings 10–19). - Applications:
- Process time-series data.
- Analyze material test results.
- Manage construction schedules.
Task 1: Load Analysis on a Bridge Girder
Problem: Calculate the total and average load from a list of daily truck loads (kN).
Sample Input:
daily_loads = [1200, 1450, 980, 1670, 1320]
Sample Output:
Total Load: 6620 kN
Average Load: 1324.0 kN
Solution Code:
daily_loads = [1200, 1450, 980, 1670, 1320]
total_load = sum(daily_loads)
average_load = total_load / len(daily_loads)
print(f"Total Load: {total_load} kN")
print(f"Average Load: {average_load:.1f} kN")
Task 2: Structural Member Forces Using Indexing
Problem: Extract shear forces for specific days from a list.
Sample Input:
shear_forces = [45.2, 52.1, 48.9, 55.3, 49.8] # Monday-Friday
Sample Output:
Wednesday's Shear Force: 48.9 kN
Friday's Shear Force: 49.8 kN
Solution Code:
shear_forces = [45.2, 52.1, 48.9, 55.3, 49.8]
# Indexing starts at 0 (Monday = 0, Wednesday = 2, Friday = 4)
wednesday = shear_forces[2]
friday = shear_forces[4]
print(f"Wednesday's Shear Force: {wednesday} kN")
print(f"Friday's Shear Force: {friday} kN")
Task 3: Soil Layer Analysis with Slicing
Problem: Extract soil layer data from a list of layer depths (meters).
Sample Input:
layer_depths = [0.5, 1.2, 2.0, 3.5, 4.8, 6.0] # Depth at each layer interface
Sample Output:
Top 3 Layers: [0.5, 1.2, 2.0]
Layer 2-4 Depths: [1.2, 2.0, 3.5]
Solution Code:
layer_depths = [0.5, 1.2, 2.0, 3.5, 4.8, 6.0]
top_layers = layer_depths[:3] # First 3 layers (indices 0, 1, 2)
layers_2_to_4 = layer_depths[1:4] # Layers at indices 1, 2, 3 (depths 1.2–3.5m)
print(f"Top 3 Layers: {top_layers}")
print(f"Layer 2-4 Depths: {layers_2_to_4}")
Task 4: Construction Schedule with Nested Lists
Problem: Track weekly tasks using nested lists and access specific tasks.
Sample Input:
schedule = [
["Excavation", "Foundation"], # Week 1
["Concrete Pour", "Steel Fixing"], # Week 2
["Curing", "Inspection"] # Week 3
]
Sample Output:
Week 2 Tasks: ['Concrete Pour', 'Steel Fixing']
Day 1 of Week 3: Curing
Solution Code:
schedule = [
["Excavation", "Foundation"],
["Concrete Pour", "Steel Fixing"],
["Curing", "Inspection"]
]
week2_tasks = schedule[1] # Index 1 = Week 2
day1_week3 = schedule[2][0] # Week 3 (index 2), Day 1 (index 0)
print(f"Week 2 Tasks: {week2_tasks}")
print(f"Day 1 of Week 3: {day1_week3}")
Key Takeaways
- Data Organization: Use lists to store sequences of engineering data (e.g., loads, depths).
- Efficient Access: Indexing/slicing extracts specific values or subsets for analysis.
- Nested Lists: Model complex schedules or layered systems (e.g., soil profiles).
Challenge Problem
Problem: Analyze concrete strength test results from a list.
- Identify tests below the 30 MPa threshold.
- Calculate the compliance rate (% of tests ≥ 30 MPa).
Sample Input:
“`python
strength_tests = [28.5, 32.1, 29.9, 31.5, 27.8, 33.4]
**Sample Output**:
Low Strength Tests: [28.5, 29.9, 27.8]
Compliance Rate: 50.0%
**Solution Code**:
python
strength_tests = [28.5, 32.1, 29.9, 31.5, 27.8, 33.4]
threshold = 30.0
low_strength = [test for test in strength_tests if test < threshold]
compliance_rate = (len(strength_tests) – len(low_strength)) / len(strength_tests) * 100
print(f”Low Strength Tests: {low_strength}”)
print(f”Compliance Rate: {compliance_rate:.1f}%”)
“`