0% found this document useful (0 votes)
2 views

programming with python - rahul

This document is a practical file for a programming course focused on Python, submitted by a BCA final year student. It includes various programming exercises with example code and explanations for tasks such as summing and multiplying list items, finding the largest and smallest numbers, and removing duplicates from lists. The file serves as a comprehensive guide for students to learn and practice Python programming concepts.

Uploaded by

tnewbie81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

programming with python - rahul

This document is a practical file for a programming course focused on Python, submitted by a BCA final year student. It includes various programming exercises with example code and explanations for tasks such as summing and multiplying list items, finding the largest and smallest numbers, and removing duplicates from lists. The file serves as a comprehensive guide for students to learn and practice Python programming concepts.

Uploaded by

tnewbie81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

A PRACTICAL FILE

ON
PROGRAMMING WITH PYTHON

SESSION: 2024-2025

SUBMITTED TO: SUBMITTED BY:


Ms. Pooja Rahul
(Assistant Professor BCA Final Year
in Computer Science) Roll no. 1221733011032
University Roll no.
221602014031

Department of Management & Computer Science


VAISH COLLEGE BHIWANI
CBLU UNIVERSITY, BHIWANI

1
2
INDEX
Sr.No. TOPICS Pg.No.

1. Write a python program to sum all the items in a list. 4-5

2. Write a python program to multiply all the items in a list. 6-8

3. Write a python program to get the largest number from a list. 9-11

4. Write a python program to get the smallest number from a list. 12-14

5. Write a python program to count the number of strings where the string length 15-17
is 2 or more and the first and last character are same from a given list of strings.
Sample list:[‘abe’, ‘xyz’, ‘aba’, ‘1221’]

6. Write a python program to get a list, sorted in increasing order by the last 18-20
element in each tuple from a given list of non-empty tuples. Sample list: [(2,5),
(1,2), (4,4), (2,3), (2,1)] Expected result: [(2,1),(1,2),(2,3),(4,4),(2,5)]

7. Write a python program to remove duplicates from a list. 21-23

8. Write a python program to check a list is empty or not. 24-27

9. Write a python program to clone or copy a list. 28-31

10. Write a python program to find the list of words that are longer than n from a 32-35
given list of words.

3
1. WRITE A PYTHON PROGRAM TO SUM ALL THE ITEMS IN A LIST

# Method 1: Using sum() function


def sum_list1(numbers):
return sum(numbers)

# Method 2: Using a for loop


def sum_list2(numbers):
total = 0
for num in numbers:
total += num
return total

# Example usage
my_list = [1, 2, 3, 4, 5]

# Using Method 1
result1 = sum_list1(my_list)
print("Sum using sum() function:", result1)

# Using Method 2
result2 = sum_list2(my_list)
print("Sum using for loop:", result2)

This program provides two different ways to sum a list:

1. Using Python's built-in sum() function (simplest method)


2. Using a for loop to iterate through each item

When you run this program with the example list [1, 2, 3, 4, 5],

Both methods will give you the same result. The sum() function is generally preferred as it's more
concise and built into Python, but the loop method shows how you could do it manually if needed.

4
OUTPUT:

5
2. WRITE A PYTHON PROGRAM TO MULTIPLY ALL THE ITEMS IN A
LIST

# Method 1: Using a for loop


def multiply_list1(numbers):
result = 1 # Start with 1 (multiplicative identity)
for num in numbers:
result *= num
return result

# Method 2: Using math.prod() (Python 3.8+)


from math import prod

def multiply_list2(numbers):
return prod(numbers)

# Example usage
my_list = [1, 2, 3, 4, 5]

# Using Method 1
result1 = multiply_list1(my_list)
print("Product using for loop:", result1)

# Using Method 2
result2 = multiply_list2(my_list)
print("Product using math.prod():", result2)

This program provides two ways to multiply all items in a list:

1. Using a for loop to multiply each item iteratively


2. Using Python's math.prod() function (available in Python 3.8 and later)

When you run this program with the example list [1, 2, 3, 4, 5],

Both methods will give you the same result (1 × 2 × 3 × 4 × 5 = 120).

Key points:

6
 We start with 1 (not 0) because multiplying by 0 would always give 0
 math.prod() is simpler but requires Python 3.8 or later
 The for loop method works in all Python versions

You can modify my_list to contain any numbers you want to multiply. The program assumes the
list contains numbers (integers or floats).

7
OUTPUT:

8
3. WRITE THE PYTHON PROGRAM TO GET THE LARGEST NUMBER
FROM A LIST

# Method 1: Using max() function


def find_largest1(numbers):
return max(numbers)

# Method 2: Using a for loop


def find_largest2(numbers):
largest = numbers[0] # Start with first element
for num in numbers:

if num > largest:


largest = num
return largest

# Example usage
my_list = [4, 2, 7, 1, 9, 5]

# Using Method 1
result1 = find_largest1(my_list)
print("Largest using max() function:", result1)

# Using Method 2
result2 = find_largest2(my_list)
print("Largest using for loop:", result2)

This program provides two ways to find the largest number in a list:

1. Using Python's built-in max() function (simplest method)


2. Using a for loop to compare each item

When you run this program with the example list [4, 2, 7, 1, 9, 5],

Both methods will give you the same result. The max() function is generally preferred as it's more
concise and optimized, but the loop method shows how you could do it manually.

9
Notes:

 The program assumes the list is not empty


 It works with integers or floats
 If the list contains only one number, that number will be returned

10
OUTPUT:

11
4. WRITE THE PYTHON PROGRAM TO GET THE SMALLEST NUMBER
FROM A LIST

# Method 1: Using min() function


def find_smallest_number(numbers):
if not numbers: # Check if list is empty
return "List is empty"
return min(numbers)

# Method 2: Using a loop


def find_smallest_loop(numbers):
if not numbers: # Check if list is empty
return "List is empty"

smallest = numbers[0] # Start with first number


for num in numbers:
if num < smallest:
smallest = num

return smallest

# Test the functions


numbers_list = [5, 2, 8, 1, 9, 3]
print("Using min() function:", find_smallest_number(numbers_list))
print("Using loop:", find_smallest_loop(numbers_list))

# Additional test cases


empty_list = []
negative_list = [-5, -2, -8, -1]
print("Empty list:", find_smallest_number(empty_list))
print("Negative numbers:", find_smallest_number(negative_list))

This program provides two methods to find the smallest number:

12
1. Using Python's built-in min() function (simplest approach)
2. Using a loop to manually compare numbers (shows the logic)

Key features:

 Both methods handle empty lists by returning a message


 Works with positive and negative numbers
 The min() function is more efficient for general use
 The loop method helps understand the logic behind finding the minimum

13
OUTPUT:

14
5. WRITE A PYTHON PROGRAM TO COUNT THE NUMBER OF
STRINGS WHERE THE STRING LENGTH IS 2 OR MORE AND THE
FIRST AND LAST CHARACTER ARE SOME FROM A GIVEN LIST OF
STRINGS. SAMPLE LIST:['abe', 'xyz', 'aba', '1221']

def count_matching_strings(string_list):
# Initialize counter
count = 0

# Iterate through each string in the list


for string in string_list:
# Check if length is 2 or more and first/last characters match
if len(string) >= 2 and string[0] == string[-1]:
count += 1

return count

# Test the function


sample_list = ['abe', 'xyz', 'aba', '1221']
result = count_matching_strings(sample_list)
print(f"Number of matching strings: {result}")

# Additional test cases


test_list1 = ['aa', 'b', 'cdc', 'xy']
test_list2 = ['hello', 'radar', 'python', 'deked']
empty_list = []

print(f"Test case 1: {count_matching_strings(test_list1)}")


print(f"Test case 2: {count_matching_strings(test_list2)}")
print(f"Empty list: {count_matching_strings(empty_list)}")

This program:

15
1. Defines a function count_matching_strings that takes a list of strings as input
2. Uses a counter variable to keep track of matching strings
3. Checks two conditions for each string:
o Length is 2 or more (len(string) >= 2)
o First character equals last character (string[0] == string[-1])
4. Returns the total count of matching strings

For the sample list ['abe', 'xyz', 'aba', '1221']:

 'abe' → length ≥ 2, but 'a' ≠ 'e' (no match)


 'xyz' → length ≥ 2, but 'x' ≠ 'z' (no match)
 'aba' → length ≥ 2, and 'a' = 'a' (match)
 '1221' → length ≥ 2, and '1' = '1' (match)

The program handles:

 Empty lists (returns 0)


 Strings of various lengths
 Single-character strings (won't count them as length < 2)
 Multiple test cases

16
OUTPUT:

17
6. WRITE A PYTHON PROGRAM TO GET A LIST, SORTED IN
INCREASING ORDER BY THE LAST ELEMENT IN EACH TUPLE FROM
A GIVEN LIST OF NON-EMPTY TUPLES. SAMPLE LIST:
[(2,5),(1,2),(4,4),(2,3),(2,1)] EXPECTED RESULT: [(2,1),(1,2),(2,3),(4,4),(2,5)]

def sort_by_last_element(tuple_list):
# Sort using sorted() with a key function that returns the last element
return sorted(tuple_list, key=lambda x: x[-1])

# Test the function


sample_list = [(2,5), (1,2), (4,4), (2,3), (2,1)]
result = sort_by_last_element(sample_list)
print("Sorted list:", result)

# Additional test cases


test_list1 = [(1,3), (2,1), (3,2)]
test_list2 = [(5,5), (4,4), (3,3)]
test_list3 = []

print("Test case 1:", sort_by_last_element(test_list1))


print("Test case 2:", sort_by_last_element(test_list2))
print("Empty list:", sort_by_last_element(test_list3))

This program:

1. Defines a function sort_by_last_element that takes a list of tuples as input


2. Uses Python's sorted() function with a key parameter
3. The key=lambda x: x[-1] tells sorted() to use the last element (x[-1]) of each tuple as the
sorting criterion
4. Returns the sorted list in increasing order based on the last element

How it works with the sample list [(2,5), (1,2), (4,4), (2,3), (2,1)]:

 Looks at last elements: 5, 2, 4, 3, 1


 Sorts them: 1, 2, 3, 4, 5
 Returns corresponding tuples: [(2,1), (1,2), (2,3), (4,4), (2,5)]

18
Alternative implementation using the sort() method:

def sort_by_last_element_alt(tuple_list):

# Create a copy to avoid modifying the original list

result = tuple_list.copy()

result.sort(key=lambda x: x[-1])

return result

# Test it

sample_list = [(2,5), (1,2), (4,4), (2,3), (2,1)]

print("Sorted list (alt):", sort_by_last_element_alt(sample_list))

Key features:

 Works with tuples of any length (as long as they're not empty)
 Handles empty lists
 Preserves the original tuple structure
 Maintains stable sorting (if two tuples have the same last element, their original order is
preserved)
 The sorted() version creates a new list, while the sort() version modifies a copy

19
OUTPUT:

20
7. WRITE A PYTHON PROGRAM TO REMOVE DUPLICATES FROM A
LIST

# Method 1: Using set (simplest approach)


def remove_duplicates_set(input_list):
return list(set(input_list))

# Method 2: Using list comprehension with a condition


def remove_duplicates_list_comp(input_list):
seen = []
return [x for x in input_list if not (x in seen or seen.append(x))]

# Method 3: Using a loop (preserves original order)


def remove_duplicates_loop(input_list):
result = []
for item in input_list:
if item not in result:
result.append(item)
return result

# Test all methods


sample_list = [1, 2, 3, 2, 4, 1, 5, 3]
print("Original list:", sample_list)

print("Using set:", remove_duplicates_set(sample_list))


print("Using list comprehension:", remove_duplicates_list_comp(sample_list))
print("Using loop:", remove_duplicates_loop(sample_list))

# Additional test cases


mixed_list = [1, "hello", 2, "hello", 1, 3.14]

21
empty_list = []
single_item = [1]

print("\nMixed list:", remove_duplicates_set(mixed_list))


print("Empty list:", remove_duplicates_set(empty_list))
print("Single item:", remove_duplicates_set(single_item))

Each method has its advantages:

1. Set Method:
o Fastest and most concise
o Doesn't preserve original order
o Works with any hashable elements
2. List Comprehension Method:
o Preserves original order
o More readable than complex loops
o Uses extra memory for the 'seen' list
3. Loop Method:
o Preserves original order
o Most explicit and easy to understand
o Good for modification or adding conditions

Important notes:

 The set method might not preserve the original order (depends on Python version)
 All methods work with lists containing different data types (integers, strings, floats, etc.)
 For unhashable elements (like lists or dictionaries), use the loop or list comprehension
method
 All methods handle empty lists and single-item lists correctly

22
OUTPUT:

23
8. WRITE A PYTHON PROGRAM TO CHECK A LIST IS EMPTY OR NOT

# Method 1: Using len() function


def is_empty_len(input_list):
return len(input_list) == 0

# Method 2: Using direct comparison with empty list


def is_empty_compare(input_list):
return input_list == []

# Method 3: Using Python's truthiness (most pythonic)


def is_empty_truthy(input_list):
return not input_list

# Test all methods


sample_list = [1, 2, 3]
empty_list = []

print("Testing non-empty list:")


print("Using len():", is_empty_len(sample_list))
print("Using compare:", is_empty_compare(sample_list))
print("Using truthiness:", is_empty_truthy(sample_list))

print("\nTesting empty list:")


print("Using len():", is_empty_len(empty_list))
print("Using compare:", is_empty_compare(empty_list))
print("Using truthiness:", is_empty_truthy(empty_list))

# Additional test cases


single_item = [1]
nested_empty = [[]]
string_list = ["hello"]

24
print("\nAdditional tests:")
print("Single item:", is_empty_truthy(single_item))
print("Nested empty list:", is_empty_truthy(nested_empty))
print("String list:", is_empty_truthy(string_list))

Each method has its characteristics:

1. len() Method:
o Explicit and clear
o Easy to understand
o Returns True if length is 0
2. Comparison Method:
o Straightforward comparison
o Very readable
o Compares directly with empty list
3. Truthiness Method:
o Most pythonic approach
o Shortest and cleanest
o Empty lists are "falsy" in Python

Key points:

 All methods return a boolean (True/False)


 The truthiness method (not input_list) is considered the most idiomatic in Python
 All methods are reliable for checking emptiness
 Works with lists containing any type of elements

Here's a practical example with user input:

def check_list_empty():
# Get list from user

user_input = input("Enter elements separated by spaces (or press enter for empty): ")
user_list = user_input.split() if user_input else []

# Check if empty
if not user_list:
print("The list is empty")

25
else:
print("The list is not empty, it contains:", user_list)

# Run the example


check_list_empty()

26
OUTPUT:

27
9. WRITE A PYTHON PROGRAM TO CLONE OR COPY A LIST

# Method 1: Using list() constructor


def clone_list_constructor(original_list):
return list(original_list)

# Method 2: Using copy() method


def clone_list_copy(original_list):
return original_list.copy()

# Method 3: Using slice operator


def clone_list_slice(original_list):
return original_list[:]

# Method 4: Using list comprehension


def clone_list_comprehension(original_list):
return [item for item in original_list]

# Test all methods


original = [1, 2, 3, 4, 5]
print("Original list:", original)

clone1 = clone_list_constructor(original)
clone2 = clone_list_copy(original)
clone3 = clone_list_slice(original)
clone4 = clone_list_comprehension(original)

print("Clone (constructor):", clone1)


print("Clone (copy):", clone2)
print("Clone (slice):", clone3)

28
print("Clone (comprehension):", clone4)

# Verify they're different objects


print("\nModifying original to prove independence:")
original.append(6)
print("Modified original:", original)
print("Clone1 still same:", clone1)

# Test with nested lists (shallow vs deep copy)


nested_list = [1, [2, 3], 4]
print("\nTesting with nested list:")
clone_nested = clone_list_copy(nested_list)
nested_list[1][0] = 99
print("Original nested:", nested_list)
print("Clone nested:", clone_nested) # Shows shallow copy limitation

# Deep copy example using copy module


import copy
deep_clone = copy.deepcopy(nested_list)
nested_list[1][1] = 88
print("\nDeep copy test:")
print("Modified original:", nested_list)
print("Deep clone:", deep_clone)

Each method has its characteristics:

1. list() Constructor:
o Simple and readable
o Creates a new list from any iterable
2. copy() Method:
o Explicit method for copying
o Available since Python 3.3

29
3. Slice Operator:
o Traditional Python idiom
o Very concise
4. List Comprehension:
o Flexible (can modify elements during copy)
o More verbose but clear

Important notes:

 All methods above create a shallow copy


 Shallow copy means nested objects (like lists within lists) still share references
 For a deep copy (complete independence including nested objects), use copy.deepcopy()
 All methods work with lists of any size and element type

Practical example with verification:

def demonstrate_copy():
original = [1, 2, ["a", "b"]]
clone = clone_list_copy(original)

# Modify original
original[0] = 99
original[2][0] = "z"

print("Original after modification:", original)


print("Clone after modification:", clone)
demonstrate_copy()
# Shows top-level independence but nested list modification affects both

30
OUTPUT:

31
10. WRITE A PYTHON PROGRAM TO FIND THE LIST OF WORDS THAT
ARE LONGER THAN N FROM A GIVEN LIST OF WORDS

# Method 1: Using a simple loop


def find_longer_words_loop(word_list, n):
result = []
for word in word_list:
if len(word) > n:
result.append(word)
return result

# Method 2: Using list comprehension


def find_longer_words_comp(word_list, n):
return [word for word in word_list if len(word) > n]

# Method 3: Using filter and lambda


def find_longer_words_filter(word_list, n):
return list(filter(lambda word: len(word) > n, word_list))

# Test all methods


sample_list = ["cat", "elephant", "dog", "hippopotamus", "rat", "kangaroo"]
n=3

print("Original list:", sample_list)


print("Words longer than", n, "characters:")
print("Using loop:", find_longer_words_loop(sample_list, n))
print("Using comprehension:", find_longer_words_comp(sample_list, n))
print("Using filter:", find_longer_words_filter(sample_list, n))

# Additional test cases


test_list1 = ["a", "ab", "abc", "abcd"]
test_list2 = []

32
test_list3 = ["python", "java", "c"]

print("\nAdditional tests:")
print("Test 1 (n=2):", find_longer_words_comp(test_list1, 2))
print("Test 2 (n=5):", find_longer_words_comp(test_list2, 5))
print("Test 3 (n=4):", find_longer_words_comp(test_list3, 4))

Each method achieves the same goal with different approaches:

1. Loop Method:
o Explicit and easy to understand
o Builds result list incrementally
2. List Comprehension Method:
o Concise and pythonic
o Single-line solution
3. Filter Method:
o Functional programming style
o Uses lambda function for condition

For the sample list ["cat", "elephant", "dog", "hippopotamus", "rat", "kangaroo"] with n = 3:

 "cat" (3) → not included (≤ 3)


 "elephant" (8) → included (> 3)
 "dog" (3) → not included (≤ 3)
 "hippopotamus" (12) → included (> 3)
 "rat" (3) → not included (≤ 3)
 "kangaroo" (8) → included (> 3)

Key features:

 All methods handle empty lists


 Works with any positive integer n
 Case-sensitive (length only counts characters)
 Returns a new list without modifying the original

Practical example with user input:

def get_longer_words_user():

33
# Get input from user
words = input("Enter words separated by spaces: ").split()
try:

n = int(input("Enter minimum length (n): "))


result = find_longer_words_comp(words, n)
print(f"Words longer than {n} characters:", result)
except ValueError:
print("Please enter a valid number for n")

# Run the example


get_longer_words_user()

34
OUTPUT

35

You might also like