Python Programs on Lists
- Categories Python, Python, Python List
Python Programs on Lists:
1.Write a Python program to remove duplicates from a list.
Ans.
a = [10,20,30,20,10,50,60,40,80,50,40] dup_items = set() uniq_items = [] for x in a: if x not in dup_items: uniq_items.append(x) dup_items.add(x) print(dup_items)
2.Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
Ans.
values = input("Input some comma seprated numbers : ") list = values.split(",") tuple = tuple(list) print('List : ',list) print('Tuple : ',tuple)
3.Write a Python program to create a histogram from a given list of integers.
Ans.
def histogram( items ): for n in items: output = '' times = n while( times > 0 ): output += '*' times = times - 1 print(output) histogram([2, 3, 6, 5])
4.Write a Python program to concatenate all elements in a list into a string and return it.
Ans.
def concatenate_list_data(list): result= '' for element in list: result += str(element) return result print(concatenate_list_data([2, 50, 12, 9]))
5.Write a Python program to filter the positive numbers from a list.
Ans.
nums = [34, 1, 0, -23] print("Original numbers in the list: ",nums) new_nums = list(filter(lambda x: x >0, nums)) print("Positive numbers in the list: ",new_nums)
6.Write a Python program to remove and print every third number from a list of numbers until the list becomes empty.
Ans.
def remove_nums(int_list): #list starts with 0 index position = 3 - 1 idx = 0 len_list = (len(int_list)) while len_list>0: idx = (position+idx)%len_list print(int_list.pop(idx)) len_list -= 1 nums = [10,20,30,40,50,60,70,80,90] remove_nums(nums)
7.Write a Python function that takes a list of words and returns the longest one.
Ans.
def find_longest_word(words_list): word_len = [] for n in words_list: word_len.append((len(n), n)) word_len.sort() return word_len[-1][1] print(find_longest_word(["PHP", "Java", "Python"]))
8.Write a Python program to accept a filename from the user and print the extension of that.
Ans.
filename = input("Input the Filename: ") f = filename.split(".") print ("The extension of the file is : " + f[-1])
You may also like
Learn Python for & while
19 June, 2021
Learn Python if elif else
15 June, 2021
Python List
15 June, 2021