0% found this document useful (0 votes)
12 views7 pages

Python List and Tuple Operations

Uploaded by

iu.chan2837
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)
12 views7 pages

Python List and Tuple Operations

Uploaded by

iu.chan2837
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

✅ Python Practical Lab Manual with Solutions

✅List Operations

Program 1: Create and Display Elements of a List


# Program to create and display elements of a list

my_list = [10, 20, 30, 40, 50]


print("The list is:", my_list)

Program 2: Add, Update, and Remove Elements from a List


my_list = [1, 2, 3]
my_list.append(4) # Add
my_list[1] = 20 # Update index 1
my_list.remove(3) # Remove element 3
print("Updated list:", my_list)

Program 3: Sort a List in Ascending and Descending Order


numbers = [5, 2, 9, 1, 7]
[Link]()
print("Ascending:", numbers)

[Link](reverse=True)
print("Descending:", numbers)

Program 4: Find the Maximum and Minimum Element in a List


numbers = [10, 25, 5, 75, 30]
print("Max:", max(numbers))
print("Min:", min(numbers))

Program 5: Count Frequency of Each Element in a List


items = [1, 2, 2, 3, 3, 3, 4]
frequency = {}
for item in items:
if item in frequency:
frequency[item] += 1
else:
frequency[item] = 1

print("Frequency of elements:", frequency)

✅ List Operations (continued)

Program 6: Remove Duplicates from a List


my_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(my_list))
print("List without duplicates:", unique_list)

Program 7: Find the Sum and Average of List Elements


numbers = [10, 20, 30, 40]
total = sum(numbers)
average = total / len(numbers)
print("Sum:", total)
print("Average:", average)

Program 8: Merge Two Lists into One


list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged = list1 + list2
print("Merged list:", merged)

Program 9: Search an Element in a List


my_list = [10, 20, 30, 40, 50]
element = 30
if element in my_list:
print(f"{element} found at index {my_list.index(element)}")
else:
print(f"{element} not found")

✅ Tuple Operations
Program 10: Create and Display a Tuple
my_tuple = (10, 20, 30)
print("Tuple elements:", my_tuple)

Program 11: Access Elements Using Indexing


my_tuple = (5, 10, 15, 20)
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])

Program 12: Slice a Tuple


my_tuple = (1, 2, 3, 4, 5)
print("Sliced Tuple (index 1 to 3):", my_tuple[1:4])

Program 13: Find the Length, Max, and Min in a Tuple


my_tuple = (8, 2, 10, 4)
print("Length:", len(my_tuple))
print("Max:", max(my_tuple))
print("Min:", min(my_tuple))

Program 14: Convert List to Tuple and Vice Versa


list1 = [1, 2, 3]
tuple1 = tuple(list1)
print("Tuple:", tuple1)

new_list = list(tuple1)
print("List again:", new_list)

✅ Dictionary Operations

Program 15: Create and Display a Dictionary


student = {"name": "Alice", "age": 20, "grade": "A"}
print("Student Dictionary:", student)
Program 16: Add, Update, and Delete Dictionary Elements
student = {"name": "Bob"}
student["age"] = 21 # Add
student["name"] = "Robert" # Update
del student["age"] # Delete
print("Updated dictionary:", student)

Program 17: Access Dictionary Values Using Keys


person = {"name": "John", "city": "New York"}
print("Name:", [Link]("name"))
print("City:", person["city"])

Program 18: Iterate Through a Dictionary


fruits = {"apple": 2, "banana": 3, "cherry": 5}
for key, value in [Link]():
print(key, ":", value)

Program 19: Merge Two Dictionaries


dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
print("Merged Dictionary:", merged)

✅ Basic Logic and Number Programs

Program 20: Check if a Number is Palindrome


num = 121
if str(num) == str(num)[::-1]:
print("Palindrome")
else:
print("Not a palindrome")

Program 21: Reverse a Number


num = 1234
rev = 0
while num > 0:
rev = rev * 10 + num % 10
num //= 10
print("Reversed Number:", rev)

Program 22: Check Prime Number


num = 7
if num > 1:
for i in range(2, num):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")

Program 23: Generate Fibonacci Series


n = 10
a, b = 0, 1
print("Fibonacci Series:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

Program 24: Factorial Using Loop


num = 5
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial:", fact)

Program 25: Check Armstrong Number


num = 153
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print("Armstrong Number")
else:
print("Not Armstrong")
Program 26: Count Vowels in a String
string = "Hello World"
vowels = "aeiouAEIOU"
count = sum(1 for ch in string if ch in vowels)
print("Vowel Count:", count)

Program 27: Find the Largest Element in a List Without max()


numbers = [10, 25, 5, 75, 30]
largest = numbers[0]
for num in numbers[1:]:
if num > largest:
largest = num
print("Largest element:", largest)

Program 28: Find Common Elements Between Two Lists


list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common = list(set(list1) & set(list2))
print("Common Elements:", common)

Program 29: Find Even and Odd Numbers in a List


numbers = [1, 2, 3, 4, 5, 6]
even = [num for num in numbers if num % 2 == 0]
odd = [num for num in numbers if num % 2 != 0]
print("Even:", even)
print("Odd:", odd)

Program 30: Count Positive, Negative, and Zero in a List


nums = [0, -1, 2, -3, 4, 0]
pos = neg = zero = 0

for num in nums:


if num > 0:
pos += 1
elif num < 0:
neg += 1
else:
zero += 1

print("Positive:", pos)
print("Negative:", neg)
print("Zero:", zero)

Common questions

Powered by AI

Using the 'if-else' clause inside a loop for checking prime numbers is appropriate because it allows you to terminate the process early as soon as a divisor is found, improving performance. For a number num, iterate through 2 to num - 1, and use if num % i == 0 to check divisibility. If a divisor is found, print 'Not Prime' and break the loop. This strategy reduces unnecessary checks and enhances performance by potentially reducing loop iterations .

To remove duplicates from a list in Python, you can convert the list to a set and then back to a list. This process works because a set is an unordered collection of unique elements. For example, with a list my_list = [1, 2, 2, 3, 4, 4, 5], you can remove duplicates by using unique_list = list(set(my_list)), which results in [1, 2, 3, 4, 5]. The use of a set is ideal here because it automatically handles duplicate entries .

To find the maximum element in a list without using built-in functions like max(), iterate through the list, maintaining a variable for the largest value found so far. Start by initializing the variable with the first element, then update it if you encounter a larger element: largest = numbers[0] for num in numbers[1:]: if num > largest: largest = num. This method has a computational complexity of O(n) because it requires examining each element of the list exactly once .

To count the frequency of each element in a list, you can use a dictionary to store each element as a key and its count as the corresponding value. Iterate through the list, updating the dictionary: for item in items: if item in frequency: frequency[item] += 1 else: frequency[item] = 1. This method is useful in data analysis for identifying trends, understanding distributions, or detecting outliers within a dataset .

Checking for special number properties like palindromes or Armstrong numbers can be important for specific computational tasks that involve cryptography, data validation, or educational settings. For example, identifying palindromes ensures symmetry in data, useful in encryption algorithms or when assessing data consistency. Armstrong number checks can highlight interesting numerical properties useful in teaching number theory concepts, engaging students in understanding complex number systems. Both involve pattern recognition, which is crucial in algorithm optimization and data science .

Merging two dictionaries in Python is beneficial when you need to combine separate data sources and manage them as a single collection. This can be efficiently achieved using the dictionary unpacking syntax, as in merged = {**dict1, **dict2}. This method is efficient and intuitive, as it combines the key-value pairs of both dictionaries into a new one, handling overlapping keys by taking values from the second dictionary if necessary .

Slicing in tuple operations allows you to create a new tuple from selected elements of an existing one, maintaining the order but not altering the original. For instance, with my_tuple = (1, 2, 3, 4, 5), slicing it like my_tuple[1:4] results in a sub-tuple (2, 3, 4). This is effective for accessing contiguous subsets of data without modifying the original tuple, particularly useful in data analysis where non-invasive operations are preferred .

List comprehensions provide a compact syntax for generating lists and can be more readable and efficient for filtering elements based on conditions, such as even or odd. Using [num for num in numbers if num % 2 == 0] for evens directly within comprehensions reduces the amount of explicit looping and conditionals, making the code more concise and often faster because it is optimized by Python's interpreter. It enhances readability by summarizing the entire operation in a single line, which is particularly useful for large-scale data processing .

In Python, you can convert a tuple to a list using the list() constructor, as in list1 = list(tuple1). Similarly, convert a list to a tuple using tuple(). These conversions imply changes from immutability to mutability. Tuples are immutable, so converting them to lists allows for modifications, whereas converting lists to tuples ensures the data cannot be altered, aiding in maintaining data integrity .

In Python, you can add an element to a list using the append() method and update an existing element by accessing its index. For example, given a list my_list = [1, 2, 3], you can add an element by calling my_list.append(4). To update an element, say at index 1, you use my_list[1] = 20. The updated list will be [1, 20, 3, 4].

You might also like