Frequently asked questions about list in Python

  • 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

OUTPUT:

[1, 5, 8, 'E', 'H', 'L', 'L', 'O']

The 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

OUTPUT:

['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

 

OUTPUT:

[[2], [9], [5]]
  • 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))

OUTPUT:

[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.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s