0% found this document useful (0 votes)
11 views6 pages

10 Beginner Python Programs Using Lists

The document presents 10 beginner-level Python programs focusing on lists, loops, inputs, and outputs. Each program demonstrates a specific task, such as finding the largest number in a list, calculating the sum and average, counting even and odd numbers, and more. These examples serve as practical exercises for learners to enhance their Python programming skills.

Uploaded by

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

10 Beginner Python Programs Using Lists

The document presents 10 beginner-level Python programs focusing on lists, loops, inputs, and outputs. Each program demonstrates a specific task, such as finding the largest number in a list, calculating the sum and average, counting even and odd numbers, and more. These examples serve as practical exercises for learners to enhance their Python programming skills.

Uploaded by

k.nambisan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming-Day#3 [21/10/2025]

10 slightly more advanced beginner-level Python programs using lists, loops, inputs, and
outputs.

🔢 1. Find the Largest Number in a List


# Find the largest number in a list
numbers = []

n = int(input("How many numbers? "))

for i in range(n):
num = float(input(f"Enter number {i+1}: "))
[Link](num)

largest = max(numbers)
print("The largest number is:", largest)

➕ 2. Calculate Sum and Average of List Elements


# Sum and average of list elements
numbers = []

n = int(input("Enter number of elements: "))


for i in range(n):
num = float(input(f"Enter number {i+1}: "))
[Link](num)

total = sum(numbers)
average = total / len(numbers)

print("Sum =", total)


print("Average =", average)

🧮 3. Count Even and Odd Numbers in a List


# Count even and odd numbers in a list
numbers = []

n = int(input("How many numbers? "))


for i in range(n):
num = int(input(f"Enter number {i+1}: "))
[Link](num)

even_count = 0
odd_count = 0

for num in numbers:


if num % 2 == 0:
even_count += 1
else:
odd_count += 1

print("Even numbers:", even_count)


print("Odd numbers:", odd_count)

🔁 4. Reverse a List
# Reverse a list
items = []

n = int(input("How many items? "))


for i in range(n):
item = input(f"Enter item {i+1}: ")
[Link](item)

print("Original list:", items)


[Link]()
print("Reversed list:", items)

🆕 5. Remove Duplicates from a List


# Remove duplicates from a list
items = []

n = int(input("Enter number of elements: "))


for i in range(n):
item = input(f"Enter element {i+1}: ")
[Link](item)

unique_items = list(set(items))
print("List without duplicates:", unique_items)

🔤 6. Sort Words Alphabetically


# Sort words alphabetically
words = input("Enter words separated by spaces: ").split()

[Link]()
print("Sorted words:", words)

📊 7. Find the Second Largest Number


# Find the second largest number
numbers = []
n = int(input("How many numbers? "))
for i in range(n):
num = float(input(f"Enter number {i+1}: "))
[Link](num)

[Link]()
print("Numbers in ascending order:", numbers)
print("Second largest number is:", numbers[-2])

🧠 8. Find Frequency of Each Element


# Frequency of elements in a list
items = input("Enter items separated by spaces: ").split()

frequency = {}

for item in items:


if item in frequency:
frequency[item] += 1
else:
frequency[item] = 1

print("Frequency of each element:")


for key, value in [Link]():
print(key, ":", value)

🧾 9. Store and Display Student Marks


# Store and display student marks
students = []
n = int(input("Enter number of students: "))

for i in range(n):
name = input(f"Enter name of student {i+1}: ")
mark = float(input("Enter mark: "))
[Link]([name, mark])

print("\nStudent Marks:")
for s in students:
print("Name:", s[0], " | Mark:", s[1])

💯 10. Separate Positive and Negative Numbers


# Separate positive and negative numbers
numbers = []

n = int(input("How many numbers? "))


for i in range(n):
num = float(input(f"Enter number {i+1}: "))
[Link](num)

positive = []
negative = []

for num in numbers:


if num >= 0:
[Link](num)
else:
[Link](num)
print("Positive numbers:", positive)
print("Negative numbers:", negative)

Common questions

Powered by AI

To extend the program calculating the frequency of each element in a list to also identify the most frequent element, add logic to find the maximum frequency and track corresponding elements: 1. Use a dictionary to count occurrences of each element. 2. Iterate through this dictionary to find the highest frequency and corresponding elements. Here's an enhanced version of the program: ``` items = input("Enter items separated by spaces: ").split() frequency = {} for item in items: if item in frequency: frequency[item] += 1 else: frequency[item] = 1 max_frequency = 0 most_frequent_item = None for item, count in frequency.items(): if count > max_frequency: max_frequency = count most_frequent_item = item print("Frequency of each element:") for key, value in frequency.items(): print(key, ":", value) print("Most frequent element is:", most_frequent_item, "with frequency:", max_frequency) ``` This method ensures all elements are counted, then identifies the element with the maximum count, efficiently utilizing the dictionary to keep complexity manageable. [Derived from Source 1]

To extend the student mark storage program to include additional details like age and grade, modify the data structure to store each student's information in a dictionary within a list. This approach groups related data logically. - Use a list of dictionaries, each storing detailed student information. - Update input and output sections of the program to accommodate new data fields. Here is how the program could be adapted: ``` students = [] n = int(input("Enter number of students: ")) for i in range(n): student = {} student['name'] = input(f"Enter name of student {i+1}: ") student['mark'] = float(input("Enter mark: ")) student['age'] = int(input("Enter age: ")) student['grade'] = input("Enter grade: ") students.append(student) print("\nStudent Information:") for student in students: print(f"Name: {student['name']} | Mark: {student['mark']} | Age: {student['age']} | Grade: {student['grade']}") ``` This strategy ensures scalable data handling by allowing easy addition of new fields, maintaining clarity and logical data grouping without unnecessary complexity.

The approach for finding the second largest number by sorting the list is straightforward but not optimal for performance, as sorting has a time complexity of O(n log n). A linear approach can be more efficient: - Iteratively find the two largest distinct numbers in one pass, reducing complexity to O(n). - Initialize two variables to track the largest and second-largest numbers. - Traverse each element to update these variables appropriately. This avoids needless sorting, particularly beneficial for large datasets. Here’s a more efficient approach: ``` numbers = [] n = int(input("How many numbers? ")) for i in range(n): num = float(input(f"Enter number {i+1}: ")) numbers.append(num) if len(numbers) < 2: print("Need at least two numbers!") else: first, second = float('-inf'), float('-inf') for num in numbers: if num > first: first, second = num, first elif num > second and num != first: second = num if second == float('-inf'): print("There is no distinct second largest number.") else: print("Second largest number is:", second) ``` This approach directly iterates to isolate the two largest distinct values, avoiding unnecessary overhead from sorting.

To find both the smallest and largest numbers in a list using only one loop, maintain two variables that track the minimum and maximum values encountered during iteration: 1. Initialize two variables, `smallest` and `largest`, with the first element of the list. 2. Iterate through the list starting from the second element. 3. For each element, update `smallest` if the current element is smaller, and update `largest` if it's larger. Here's how this can be implemented: ``` numbers = [] n = int(input("How many numbers? ")) for i in range(n): num = float(input(f"Enter number {i+1}: ")) numbers.append(num) if numbers: smallest, largest = numbers[0], numbers[0] for number in numbers[1:]: if number < smallest: smallest = number if number > largest: largest = number else: smallest, largest = None, None print("Smallest number is:", smallest) print("Largest number is:", largest) ``` This method optimizes by completing both tasks in a single pass, reducing runtime complexity from O(2n) to O(n). [Derived from Source 1]

The original algorithm for separating positive and negative numbers typically involves iterating over the list once to check each number's sign and then appending it either to a positive or negative list, which has a time complexity of O(n). To preserve the original order while separating, maintain separate lists from the original iteration instead of re-sorting. This ensures that the elements retain their relative order in each resulting list by following these steps: 1. Initialize two lists, `positive` and `negative`, before iteration. 2. Traverse the input list, appending positive numbers to `positive` and negative numbers to `negative`. Here's an example: ``` numbers = [] n = int(input("How many numbers? ")) for i in range(n): num = float(input(f"Enter number {i+1}: ")) numbers.append(num) positive = [num for num in numbers if num >= 0] negative = [num for num in numbers if num < 0] print("Positive numbers:", positive) print("Negative numbers:", negative) ``` This modification directly separates positives and negatives while maintaining the input's order within each subgroup, thus adhering to O(n) complexity.

To handle an empty list in the sum and average calculation function, you need to introduce checks before performing division, as division by zero is undefined. Here's how to do it: - First, check if the list is empty before performing operations. - If it is empty, you can set the total sum to 0 and the average to a special value, like None or 0, depending on the context. - If the list isn't empty, proceed with the normal calculation. Here is an example: ``` numbers = [] n = int(input("Enter number of elements: ")) for i in range(n): num = float(input(f"Enter number {i+1}: ")) numbers.append(num) if len(numbers) == 0: total = 0 average = None else: total = sum(numbers) average = total / len(numbers) print("Sum =", total) print("Average =", average if average is not None else "Undefined") ``` This approach prevents division errors by checking the list length before calculating the average.

To make the sorting of words case-insensitive, modify the sorting logic to compare words in lowercase or uppercase consistently. Python's `sort()` function can accept a key parameter to specify a transformation prior to comparison: Use the `str.lower` function to convert all words to lowercase for comparison: ``` words = input("Enter words separated by spaces: ").split() words.sort(key=str.lower) print("Sorted words:", words) ``` This ensures that the original casing of the words is preserved while performing the comparison on their lowercase versions. This approach modifies the sorting operation's key to neutralize case effects, maintaining original data integrity while achieving desired ordering.

To optimize the algorithm for removing duplicates from a list without using set operations, consider implementing a manual check for duplicates using a secondary list structure: - Iterate over the input list and use a secondary list (or dictionary) to keep track of seen elements. - Only append elements to the result list if they haven’t been seen before. - This avoids the overhead of converting a list to a set and back but is typically less efficient in Python due to O(n^2) complexity compared to the set’s O(n) operations. - Here’s a sample implementation: ``` items = [] n = int(input("Enter number of elements: ")) for i in range(n): item = input(f"Enter element {i+1}: ") items.append(item) unique_items = [] seen = set() for item in items: if item not in seen: unique_items.append(item) seen.add(item) print("List without duplicates:", unique_items) ``` This method maintains a list of unique items by checking each item against a set of previously encountered items. This approach balances readability and performance. [Derived from Source 1]

To modify the algorithm for finding the largest number in a list to also return its position, you need to keep track of the index as you iterate through the list. Initialize a variable to store the position of the largest number, and update this variable whenever a new largest number is found as shown in this pseudocode: ``` numbers = [] n = int(input("How many numbers? ")) for i in range(n): num = float(input(f"Enter number {i+1}: ")) numbers.append(num) largest = numbers[0] position = 0 for i in range(1, len(numbers)): if numbers[i] > largest: largest = numbers[i] position = i print("The largest number is:", largest, "at position:", position) ``` The algorithm checks each element to see if it's greater than the current largest element. When it finds one, it updates both the largest element and its position. [Derived from Source 1]

Using list comprehensions instead of for loops to separate even and odd numbers from a list maximizes Python's efficiency and succinctness. List comprehensions translate into shorter lines of code, improve readability, potentially lead to faster execution, and are pythonic: - They consolidate logic into a single line, reducing boilerplate code compared to for loops. - Python’s interpreter can optimize comprehensions better than equivalent loops due to their specific syntax. - Enhanced readability makes the code easier to understand and maintain. For instance, separating even and odd numbers using list comprehension: ``` numbers = [int(input(f"Enter number {i+1}: ")) for i in range(int(input("How many numbers? ")))] evens = [num for num in numbers if num % 2 == 0] odds = [num for num in numbers if num % 2 != 0] print("Even numbers:", evens) print("Odd numbers:", odds) ``` This approach reduces noise in the code and makes the separation logic's intent clearer. Comprehensions enhance performance by reducing overhead from repeated function calls and loop construct evaluations.

You might also like