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
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
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
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
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]:
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
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
In [ ]: