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

Python List Methods and Examples

The document contains a series of Python programming tasks demonstrating various list methods and operations. Each task includes a description, sample input, and the expected output, covering topics such as list manipulation, filtering, shuffling, finding prime numbers, and more. The document serves as a practical guide for learning and applying Python list functionalities.

Uploaded by

Aditya Kumar
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)
4 views7 pages

Python List Methods and Examples

The document contains a series of Python programming tasks demonstrating various list methods and operations. Each task includes a description, sample input, and the expected output, covering topics such as list manipulation, filtering, shuffling, finding prime numbers, and more. The document serves as a practical guide for learning and applying Python list functionalities.

Uploaded by

Aditya Kumar
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

Q1. Write a program in Python to demonstrate following methods of a list.

Python List Methods

Python has many useful list methods that make it really easy to work with lists.

Method Description

append() Adds an item to the end of the list

extend() Adds items of lists and other iterables to the end of the list

insert() Inserts an item at the specified index

remove() Removes the specified value from the list

pop() Returns and removes item present at the given index

clear() Removes all items from the list

index() Returns the index of the first matched item

count() Returns the count of the specified item in the list

sort() Sorts the list in ascending/descending order

reverse() Reverses the item of the list

copy() Returns the shallow copy of the list

Q2. Write a Python program to print a specified list after removing the 0th, 4th and
5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black']
Ans- # Create a list 'color' with several color strings
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

# Use a list comprehension to create a new list 'color' that includes elements from the
original list
# but only if their index (i) is not in the specified indices (0, 4, 5)
color = [x for (i, x) in enumerate(color) if i not in (0, 4, 5)]

# Print the modified 'color' list, which excludes elements at indices 0, 4, and 5
print(color)
Q3. Write a Python program to print the numbers of a specified list after removing
even numbers from it.
Ans-# Create a list 'num' containing several integer values
num = [7, 8, 120, 25, 44, 20, 27]

# Use a list comprehension to create a new list 'num' that includes only the elements
from the original list
# where the element is not divisible by 2 (i.e., not even)
num = [x for x in num if x % 2 != 0]

# Print the modified 'num' list, which contains only odd values
print(num)

Q4. Write a Python program to shuffle and print a specified list.


Ans-
# Import the 'shuffle' function from the 'random' module, which is used for shuffling
the elements in a list
from random import shuffle

# Create a list 'color' with several color strings


color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

# Use the 'shuffle' function to randomly reorder the elements in the 'color' list
shuffle(color)

# Print the shuffled 'color' list, which will have its elements in a random order
print(color)

Q5. Write a Python program to check if each number is prime in a given list of
numbers. Return True if all numbers are prime otherwise False.
Sample Data:
([0, 3, 4, 7, 9]) -> False
([3, 5, 7, 13]) -> True
([1, 5, 3]) -> False
Ans- # Define a function named 'test' that takes a list 'nums' as a parameter
def test(nums):
# Use a generator expression to check if each number in 'nums' is prime, and return
True if all are prime
return all(is_prime(i) for i in nums)

# Define a function named 'is_prime' that checks if a number 'n' is prime


def is_prime(n):
# Check if 'n' is equal to 1; if so, it's not prime
if (n == 1):
return False
# Check if 'n' is equal to 2; if so, it's prime
elif (n == 2):
return True
else:
# Iterate through numbers from 2 to 'n' - 1
for x in range(2, n):
# If 'n' is divisible by 'x', it's not prime; return False
if (n % x == 0):
return False
# If no divisors were found, 'n' is prime; return True
return True

# Define a list 'nums' containing a sequence of numbers


nums = [0, 3, 4, 7, 9]
# Print the original list of numbers
print("Original list of numbers:")
print(nums)
# Check if each number in 'nums' is prime and print the result
print("Check if each number is prime in the said list of numbers:")
print(test(nums))

# Reassign 'nums' with a different list of numbers


nums = [3, 5, 7, 13]
# Print the original list of numbers
print("\nOriginal list of numbers:")
print(nums)
# Check if each number in the new 'nums' list is prime and print the result
print("Check if each number is prime in the said list of numbers:")
print(test(nums))

# Reassign 'nums' with another list of numbers


nums = [1, 5, 3]
# Print the original list of numbers
print("\nOriginal list of numbers:")
print(nums)
# Check if each number in the new 'nums' list is prime and print the result
print("Check if each number is prime in the said list of numbers:")
print(test(nums))

Q6. Write a Python program to calculate the difference between the two lists.
Ans- # Define a list 'list1' containing numbers
list1 = [1, 3, 5, 7, 9]

# Define another list 'list2' containing different numbers


list2 = [1, 2, 4, 6, 7, 8]

# Calculate the difference between 'list1' and 'list2' by converting them to sets and
subtracting the sets
diff_list1_list2 = list(set(list1) - set(list2))
# Calculate the difference between 'list2' and 'list1' by converting them to sets and
subtracting the sets
diff_list2_list1 = list(set(list2) - set(list1))

# Concatenate the differences 'diff_list1_list2' and 'diff_list2_list1' to obtain a list of


all unique differences
total_diff = diff_list1_list2 + diff_list2_list1

# Print the total difference, which represents elements that are unique to each list
print(total_diff)

Q7. Write a Python program to flatten a shallow list.


Ans- # Import the 'itertools' module, which provides various functions for working
with iterators
import itertools

# Define a list 'original_list' containing nested sublists


original_list = [[2, 4, 3], [1, 5, 6], [9], [7, 9, 0]]

# Use '[Link]' and the unpacking operator (*) to merge the sublists into a
single flat list
new_merged_list = list([Link](*original_list))

# Print the newly merged list 'new_merged_list'


print(new_merged_list)

One more answer- # Define a function named 'flatten' that takes a list of lists 'nums'
and flattens it into a single list
def flatten(nums):
# Use a list comprehension to iterate through the sublists 'y' and the elements 'x'
within each sublist
return [x for y in nums for x in y]

# Define a list 'nums' containing nested sublists


nums = [[1, 2, 3, 4], [5, 6, 7, 8]
print("Original list elements:")
# Print the original list 'nums'
print(nums)

# Print a newline for separation


print("\nFlatten the said list:")
# Call the 'flatten' function to flatten the 'nums' list and print the result
print(flatten(nums)

# Reassign 'nums' with a different list of nested sublists


nums = [[2, 4, 3], [1, 5, 6], [9], [7, 9, 0]]
print("\nOriginal list elements:")
# Print the original list 'nums'
print(nums)
# Print a newline for separation
print("\nFlatten the said list:")
# Call the 'flatten' function to flatten the new 'nums' list and print the result
print(flatten(nums))

Q8. Write a Python program to find the second smallest number in a list.
Ans-# Define a function named 'second_smallest' that takes a list of numbers
'numbers' as a parameter
def second_smallest(numbers):
# Check if the length of the 'numbers' list is less than 2; return None in this case
if len(numbers) < 2:
return

# Check if there are only two elements in the 'numbers' list, and they are the same;
return None in this case
if len(numbers) == 2 and numbers[0] == numbers[1]:
return

# Create an empty set 'dup_items' to store duplicate items and an empty list
'uniq_items' to store unique items
dup_items = set()
uniq_items = []

# Iterate through the elements in the 'numbers' list


for x in numbers:
# Check if 'x' is not in 'dup_items'; if not, add it to 'uniq_items' and 'dup_items'
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)

# Sort the 'uniq_items' list in ascending order


uniq_items.sort()

# Return the second smallest item from the sorted 'uniq_items' list, which is at
index 1
return uniq_items[1]

# Call the 'second_smallest' function with different lists and print the results
print(second_smallest([1, 2, -8, -2, 0, -2]))
print(second_smallest([1, 1, 0, 0, 2, -2, -2]))
print(second_smallest([1, 1, 1, 0, 0, 0, 2, -2, -2]))
print(second_smallest([2, 2])) # Edge case with two identical elements, returns None
print(second_smallest([2])) # Edge case with a single element, returns None

Q9. Write a Python program to check whether a list contains a sublist.


Ans-# Define a function named 'is_Sublist' that checks if list 's' is a sublist of list 'l'
def is_Sublist(l, s):
sub_set = False # Initialize a flag 'sub_set' to indicate whether 's' is a sublist of 'l
# Check if 's' is an empty list; in this case, 's' is a sublist of any list
if s == []:
sub_set = True
# Check if 's' is equal to 'l'; if so, 's' is a sublist of 'l
elif s == l:
sub_set = True
# Check if the length of 's' is greater than the length of 'l'; 's' cannot be a sublist in
this case
elif len(s) > len(l):
sub_set = False
else:
# Iterate through the elements of 'l'
for i in range(len(l)):
# Check if the current element in 'l' matches the first element in 's'
if l[i] == s[0]:
n=1
while (n < len(s)) and (l[i + n] == s[n]):
n += 1

# If 'n' equals the length of 's', 's' is a sublist of 'l


if n == len(s):
sub_set = True

# Return the value of 'sub_set,' which indicates whether 's' is a sublist of 'l

return sub_set

# Define list 'a,' 'b,' and 'c'


a = [2, 4, 3, 5, 7]
b = [4, 3]
c = [3, 7]

# Check if 'b' is a sublist of 'a' and print the result


print(is_Sublist(a, b))

# Check if 'c' is a sublist of 'a' and print the result


print(is_Sublist(a, c))

Q10. Write a Python program to create a list by concatenating a given list with a
range from 1 to n.
Sample list : ['p', 'q']
n =5
Sample Output : ['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4', 'p5', 'q5']
Ans-# Define a list 'my_list' containing elements 'p' and 'q'
my_list = ['p', 'q']

# Define a variable 'n' with the value 4


n=4
# Use a list comprehension to create a new list 'new_list' by combining elements from
'my_list' with numbers from 1 to 'n'
new_list = ['{}{}'.format(x, y) for y in range(1, n+1) for x in my_list]

# Print the 'new_list' containing combinations of elements from 'my_list' and numbers
print(new_list)

Q11. Write a Python program to find missing and additional values in two lists.
Sample data : Missing values in second list: b,a,c
Additional values in second list: g,h
Ans- # Define two lists 'list1' and 'list2' containing elements
list1 = ['a', 'b', 'c', 'd', 'e', 'f']
list2 = ['d', 'e', 'f', 'g', 'h']

# Calculate the missing values in 'list2' by finding the set difference between 'list1'
and 'list2'
missing_values = set(list1).difference(list2)

# Print the missing values in the second list 'list2'


print('Missing values in the second list: ', ','.join(missing_values))

# Calculate the additional values in 'list2' by finding the set difference between 'list2'
and 'list1'
additional_values = set(list2).difference(list1)

# Print the additional values in the second list 'list2'


print('Additional values in the second list: ', ','.join(additional_values))

Q12. Write a Python program to split a list every Nth element.


Sample list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
Expected Output: [['a', 'd', 'g', 'j', 'm'], ['b', 'e', 'h', 'k', 'n'], ['c', 'f', 'i', 'l']]

Ans- # Define a list 'C' containing alphabetic characters from 'a' to 'n'
C = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']

# Define a function 'list_slice' that takes a sequence 'S' and a 'step' value
# The function returns a list of slices from 'S' with a step of 'step'
def list_slice(S, step):
return [S[i::step] for i in range(step)]

# Call the 'list_slice' function with the list 'C' and a step value of 3
# The function generates slices of 'C' with a step of 3 and returns a list of these slices
# Print the resulting list of slices
print(list_slice(C, 3))

You might also like