Python Practice
Set 2
Q1. Create a list in python using the followings: 2,3,4,5,6,7 with variable ‘a’
Add ‘mango to the above list
Also add banana, grapes & orange in the list
insert apple in the 5th position of a variable ‘a’
Remove last item from the list
Q2.
L = [1,2,3,4,5,6,7]
Using the above list slice from 1:4
Q3. Reverse the order of given string L = [4,5,6,8,3] Without using reverse() function.
Q4. Use list comprehension to square the given list L=[2,4,7,3,6,8]
Q5. Create a function that takes in a tuple of integers and returns the sum of the integers. Test the
function with a tuple of your choice.
Q6. Create two sets of your favourite fruits, and use the union() method to combine them into a single set.
Print the resulting set to the console.
Q7. Create a set of random words, and use the add() method to add a new word to the set. Print the
resulting set to the console.
Q8. Create a set of your favourite animals, and use the remove() method to remove one animal from the
set. Print the resulting set to the console.
Q9. favorite_books = {"1984", "To Kill a Mockingbird", "Pride and Prejudice"}
favorite_movies = ["The Shawshank Redemption", "The Godfather", "The Dark Knight"]
Use the zip() function to combine the book set and movie list into a list of tuples representing book/
movie pairs. Print the resulting list.
Q10. Write a Python program to find the difference between consecutive numbers in a list.
Solutions:
# Exercise 6
fruits1 = {"apple", "banana", "pear"}
fruits2 = {"orange", "grape", "kiwi"}
combined_fruits = [Link](fruits2)
print(combined_fruits)
# Exercise 7
words = {"hello", "world", "python"}
[Link]("programming")
print(words)
Data Science Masters
# Exercise 8
animals = {"dog", "cat", "hamster", "parrot"}
[Link]("cat")
print(animals)
# Solution 9
book_movie_pairs = list(zip(favorite_books, favorite_movies))
print(book_movie_pairs)
# Solutions 10
def find_diff_consecutive_numbers(lst):
diffs = []
for i in range(1, len(lst)):
diff = lst[i] - lst[i-1]
[Link](diff)
return diffs
# example usage
my_list = [5, 9, 12, 18, 22]
diffs = find_diff_consecutive_numbers(my_list)
print(diffs) # Output: [4, 3, 6, 4]
Data Science Masters