In [8]:
# Swap variables

a = 10
b = 20
print a ," ", b

# Technique 1
a, b = b, a
print a ," ", b

# Technique 2
a = a + b
b = a - b
a = a - b
print a ," ", b

# Technique 3
x = a
a = b
b = x
print a ," ", b

# Technique 4
a = a ^ b
b = a ^ b
a = a ^ b
print a ," ", b


10   20
20   10
10   20
20   10
10   20

In [22]:
# Reverse a list.

arr = [x for x in xrange(10)]

# Technique 1 - array slicing
print arr[::-1]


# Technique 2 - reversed function
print list(reversed(arr))


# Technique 3 - Simple loop
start = 0
end = len(arr)-1
while start < end:
    arr[start], arr[end] = arr[end], arr[start]
    start += 1
    end -= 1 
print arr


[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

In [23]:
# Make a copy of a list.

arr = [x for x in xrange(10)]

# Technique 1 - array slicing.
b = arr[:]
print b


# Technique 2 - deepcopy function.
from copy import deepcopy

c = deepcopy(arr)
print c


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [12]:
"""
list1 = ['a', 'b', 'c', 'd']
list2 = ['p', 'q', 'r', 's']
Write code to print
a p
b q
c r
d slist1 = ['a', 'b', 'c', 'd']
list2 = ['p', 'q', 'r', 's']

"""
list1 = ['a', 'b', 'c', 'd']
list2 = ['p', 'q', 'r', 's']

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


a p
b q
c r
d s

In [16]:
# Create a single string from all the elements in list above.

def create_string(arr):
    if arr is None or len(arr) == 0:
        return arr
    else:
        return "".join(arr)

arr = ["Andrews", "Boateng", "Python", "Developer"]
create_string(arr)


Out[16]:
'AndrewsBoatengPythonDeveloper'

In [18]:
# What will be the output of the code below?

arr = ['a', 'b', 'c', 'd', 'e']
print arr[10:]


[]

In [19]:
# What will be the output of the code below?

class C(object):
    x = 2
    
c1 = C()
c2 = C()
print c1.x

c1.x = 101
print c1.x
print c2.x

del c1.x
print c1.x
print c2.x

C.x = 100100
print c1.x


2
101
2
2
2
100100

In [10]:
# Sort a dictionary by its value.

arr = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

# Technique 1
import operator
sorted_arr = sorted(arr.items(), key=operator.itemgetter(1))
print sorted_arr

# Technique 2
sorted_arr = sorted(arr.items(), key=lambda x: x[1])
print sorted_arr

# Technique 3


[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]

In [ ]: