[go: up one dir, main page]

0% found this document useful (0 votes)
7 views15 pages

Lab # 9 - Introduction To Python Lists and Tuples

Uploaded by

shaheerkhan1923
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Lab # 9 - Introduction To Python Lists and Tuples

Uploaded by

shaheerkhan1923
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Department of Electrical Engineering

Faculty of Engineering & Applied Sciences

Riphah International University, Lahore, Pakistan

Program: B.S Computer System Semester: 1st – Semester

Subject: CMSL 101 - Introduction to ICT Lab Date:

Experiment: #9 Introduction to Python Lists and Tuples

Student Name: SAP ID#

Lab Performance
No. Title Marks Obtained Marks

1 Understanding of Concepts 5

2 Overall Performance 5

Total 10

Lab Reports
No. Title Marks Obtained Marks

1 Organization and Structure 5

2 Data Presentation 5

Total 10

Remarks (if any):

Name & Signature of faculty:


Experiment # 9
Introduction to Python Lists and Tuples
Theory and Background
This lab aims to introduce students to Python lists and tuples, focusing on creating, accessing, modifying,
and organizing these data structures. Students will learn to use lists for dynamic data storage, manipulate
list elements, and understand the immutability of tuples. The lab includes practical exercises to reinforce
these concepts and adheres to PEP 8 style guidelines for readable code.

Lists in Python are ordered, mutable collections of items enclosed in square brackets ([]), allowing storage
of diverse data types. Tuples, enclosed in parentheses (()), are immutable, meaning their elements cannot
be changed after creation. This lab covers creating lists, accessing elements, modifying lists, sorting,
looping, slicing, copying, and working with tuples, along with common errors to avoid.

Exercise 1: Creating and Accessing Lists


Objective: Learn to create a list and access its elements using indices

Description: A list is defined using square brackets, with elements separated by commas. Indices start at
0, and negative indices (e.g.,-1) access elements from the end.

Code Example:

Explanation:

• Line 2: Creates a list bicycles with four string elements.


• Line 3: Prints the entire list, showing its representation with square brackets.
• Line 4-5: Accesses the first element (bicycles[0]) and applies the title() method to capitalize it.
• Lines6–8: Access elements at indices 1, 3, and-1 (last element).
Output:

Task 9-1: Names

• Create a list called names with at least three friends’ names.


• Print each name by accessing each element individually using indices.

Task 9-2: Greetings

• Use the names list from Task 3-1.


• Print a personalized greeting for each person, e.g., "Hello, [name]! How are you?"

Exercise 2: Modifying, Adding, and Removing Elements


Objective: Understand how to modify, add, and remove elements in a list.

Description: Lists are mutable, allowing changes to elements, addition of new elements using append()
or insert(), and removal using del, pop(), or remove().

Code Example:
Explanation:

• Line 2: Creates a list motorcycles.


• Line 6: Modifies the first element ([0]) to 'ducati'.
• Line 10: Appends 'honda' to the end of the list.
• Line 14: Inserts 'kawasaki' at index 0, shifting other elements right.
• Line 18: Deletes the element at index 1 ('ducati').
• Line 22: Pops the last element ('honda') and stores it in popped_motorcycle.
• Line 27: Removes the first occurrence of 'yamaha'.

Output:

Task 9-3: Your Own List

• Create a list of your favorite modes of transportation (e.g., ['car', 'bike', 'train']).
• Print a statement for each, e.g., "I would like to own a [item]."
Exercise 3: Guest List Management
Objective: Practice list manipulation with a dinner guest list scenario.

Description: Create a list of dinner guests and modify it through additions, removals, and updates, using
loops to print invitations.

Code Example:

Explanation:

• Lines 3–4: Loop through guests to print invitations.


• Line 7: Announce that guests[1] (Bob) can’t attend.
• Line 8: Replace Bob with David.
• Lines 14–16: Add guests using insert() (at start and middle) and append() (at end).
• Lines 22–26: Pop guests until only two remain, printing apologies.
• Lines 30–31: Delete remaining guests to empty the list.

Output:

Task 9-4: Guest List Series

• Create a list of at least three dinner guests and print invitations.


• Modify the list to replace one guest who can’t attend and print new invitations.
• Add three more guests (one at start, one in middle, one at end) and print new invitations.
• Reduce the list to two guests using pop(), print apologies, confirm remaining invitations, and
empty the list using del.
Exercise 4: Organizing Lists
Objective: Learn to sort and reverse lists using sort(), sorted(), and reverse().

Description: Lists can be sorted permanently (sort()), temporarily (sorted()), or reversed (reverse()). The
len() function returns the list length.

Code Example:

Explanation:

• Line 3: Prints the original list.


• Line 4: Uses sorted() to display the list alphabetically without changing it.
• Line 5: Confirms the original order is unchanged.
• Line 6: Uses sorted(reverse=True) for reverse alphabetical order.
• Line 7: Permanently sorts the list with sort().
• Line 9: Reverses the list order with reverse().
• Line 11: Prints the list length using len()

Output:
Task 9-5: Seeing the World

• Create a list of five places to visit, not in alphabetical order.


• Print the list in its original order.
• Use sorted() to print alphabetically and reverse alphabetically.
• Show the list remains unchanged.
• Use reverse() to reverse the list, print it, then reverse it back.
• Use sort() to sort alphabetically and reverse alphabetically.

Exercise 5: Looping Through Lists


Objective: Use for loops to iterate over lists and avoid indentation errors.

Description: A for loop processes each item in a list. Proper indentation is crucial to avoid logical or
syntax errors.

Code Example:

Explanation:

• Line 2: Defines a list magicians.


• Lines 3–5: A for loop iterates over each name, printing two messages per magician.
• Line 6: Unindented line executes once after the loop, thanking all magicians.

Output:
Task 9-6: Pizzas

• Create a list of three pizza types.


• Use a for loop to print each name and a sentence like "I like [pizza] pizza."
• Add a final statement outside the loop, e.g., "I really love pizza!"

Task 9-7: Animals

• Create a list of three animals with a common trait.


• Print each name and a statement like "A [animal] would make a great pet."
• Add a final statement about their common trait.

Exercise 6: Numerical Lists and List Comprehensions


Objective: Create numerical lists using range() and list comprehensions.

Description: The range() function generates number sequences, and list comprehen sions provide a
concise way to create lists.

Code Example:

Explanation:

• Line 2: Creates a list from 1 to 5 using range(1, 6).


• Line 5: Creates a list of even numbers from 2 to 10, stepping by 2.
• Lines 8–10: Builds a list of squares using a for loop.
• Line 14: Uses a list comprehension to create the same list of squares.
• Line 18: Applies min(), max(), and sum() to a list of digits.

Output:

Task 9-8: Numerical Lists

9.8.1 Print numbers 1 to 20 using a for loop.


9.8.2 Create a list of numbers 1 to 1,000,000 and print them (stop if too slow).
9.8.3 Create a list of 1 to 1,000,000, verify min() and max(), and compute sum().
9.8.4 Create a list of odd numbers from 1 to 20 using range().
9.8.5 Create a list of multiples of 3 from 3 to 30 and print them.
9.8.6 Create a list of the first 10 cubes using a for loop.
9.8.7 Create a list of the first 10 cubes using a list comprehension.

Exercise 7: Slicing and Copying Lists


Objective: Work with list slices and create copies of lists.

Description: Slices extract subsets of a list using [start:end:step]. Copying a list with [:] creates a new
list, avoiding shared references.

Code Example:
Explanation:

• Lines 3–7: Demonstrate various slices (e.g., [0:3] for first three elements).
• Lines 10–12: Loop through a slice to print the first three players’ names.
• Line 16: Copies my foods to friend foods using[:].
• Lines 17-18 : Add different items to each list to show they are separate.

Output:

Task 9-9: Slices

• Use a previous program to print the first three, middle three, and last three items using slices.

Task 9-10: Pizzas

• Create a pizzas list, copy it to friend_pizzas, add different pizzas to each, and print both lists
using for loops.
Exercise 8: Working with Tuples
Objective: Understand tuples and their immutability.

Description: Tuples are immutable lists defined with parentheses. They support index ing and looping
but cannot be modified.

Code Example:

Explanation:

• Line 2: Defines a tuple dimensions.


• Lines 3–5: Loops through and prints each dimension.
• Line 7: Commented-out attempt to modify the tuple (would raise TypeError).
• Line 10: Reassigns a new tuple to dimensions.

Output:

Task 9-11:

• Create a tuple of five buffet foods.


• Print each food using a for loop.
• Attempt to modify one item (observe the error).
• Rewrite the tuple with two new foods and print the new menu.
Exercise 9: Avoiding Index Errors
Objective: Learn to handle and avoid index errors.

Description: Index errors occur when accessing an invalid index. Use -1 for the last item and check list
length with len().

Code Example:

Explanation:

• Line 3: Commented-out line would cause an IndexError (index 3 is out of range).


• Line 4: Safely accesses the last element with-1.
• Line 5: Prints the list length.

Output:

Task 9-12: Intentional Error

• Modify a program to cause an index error (e.g., access motorcycles[3]).


• Correct the error by using a valid index or -1

Exercise 10: Comprehensive List Program


Objective: Use all list functions in a single program.

Code Example:
Explanation:

Uses sort(), sorted(), reverse(), append(), insert(), pop(), remove(), and len() on a list of cities.

Output:

Task 9-13: Every Function

• Create a list of items (e.g., countries, cities).


• Use each list function (append, insert, del, pop, remove, sort, sorted, reverse, len) at least once.
Style Guidelines (PEP 8)
• Use four spaces per indentation level.
• Keep lines under 80 characters (set a vertical guideline in your editor).
• Use single blank lines to separate logical sections; avoid excessive blank lines.
• Follow meaningful variable names (e.g., cities for a list of cities).

Task 9-14: PEP 8 Review

• Skim the PEP 8 style guide at https://python.org/dev/peps/pep-0008/

Task 9-15: Code Review

• Review three programs from this lab and ensure they comply with PEP 8 (four space indentation,
< 80 characters per line, minimal blank lines).

*--------------------------------------*

You might also like