Published using Google Docs
Python Tips
Updated automatically every 5 minutes

1. Reverse a string in Python

a= “Andy”

print “reverse is”, a[::-1]

2. Write code to transpose a matrix

 mat = [[1, 2, 3], [4, 5, 6]]

zip(*mat)

3. a = [1,2,3]

Store all three values of the list in 3 new variables

a1,a2,a3 = a

4. a = ["Andrews", "Boateng", "Python", "Developer"]

Create a single string from all the elements in list above.

“”.join(a)

5. list1 = ['a', 'b', 'c', 'd']

list2 = ['p', 'q', 'r', 's']

Write code to print

ap

bq

cr

ds

for i1,i2 in zip(list1,list2):

    print i1,i2

6. Swap two numbers

a=7

b=5

b,a =a,b

7. print andrewsandrewsandrewsandrews boatengboatengboatengboatengboateng

print andres*4+’ ’+boateng*5

8.a = [[1, 2], [3, 4], [5, 6]]

Convert it to a single list

output:- [1, 2, 3, 4, 5, 6]

list(itertools.chain.from_iterable(a))

print a[0]+a[1]+a[2]

9. def is_anagram(word1, word2):

    """Checks whether the words are anagrams.

    word1: string

    word2: string

    returns: boolean

    """

Complete the above method to find if two words are anagrams.

from collections import Counter

def is_anagram(str1, str2):

return Counter(str1) == Counter(str2)

10. Take string input. For example "1 2 3 4" and return [1, 2, 3, 4]. Remember return list items are integer.

map(lambda x:int(x) ,raw_input().split())