- How to convert a list to a String?
Ans: You can convert a list to a String using join() function. It will return a String which is the concatenation of the Strings in iterable. If you list contains only integers you should first convert the integer into string then only you can perform join operation on them.
list = [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] string = ''.join(list) print string
This will glue all the elements of the list and return a single String.
OUTPUT: Sunday Monday Tuesday Wednesday Thursday Friday Saturday
- How to sort a list in Python?
Ans: Sorting of list in Python can be done in two ways: first using sort() function and second using sorted() function.
a=['H', 'E', 'L', 'L', 'O', 1, 5, 8] a.sort() print a
[1, 5, 8, 'E', 'H', 'L', 'L', 'O']
sorted() function can be applied to any Iterable objects like strings, sets, dictionaries. Here we will pass a String to sorted() function and it will generate a sorted list containing every characters as different element.
a='PARIS' sorted(a) print a
['A', 'I', 'P', 'R', 'S']
- How to obtain the intersection of two lists?
Ans: filter() function can be used to get the intersection of two lists.
Let us consider we have two lists l1 and l2 and we want to get the common elements of these two lists as a list.
l1=[2, 5, 9] l2=[[19,2],[9,45],[3,6,5]] l3 = [filter(lambda x: x in l1, derivedlist) for derivedlistin l2] print l3
[, , ]
- How to remove the duplicate elements from the list?
It is easier to use set() to remove the duplicates, but don’t worry you can always convert back a set to list using list() function.
listWithDupluicates=[4, 4, 4, 6, 7, 7, 9, 0, 9, 9, 11, 11, 11, 11, 78] print list(set(listWithDupluicates))
[0, 4, 6, 7, 9, 11, 78]
So, what this basically does is convert the list with duplicate entries to set and convert that set into list.