List, tuple, and dictionary
List
It is a good idea to name lists as plural as they contain multiple elements. Like, names
, items
etc.
- Input
- Output
names = ['Rupal', 'Pranab', 'Bhanu']
print(names)
['Rupal', 'Pranab', 'Bhanu']
Lists are mutable, we can change its contents:
- Input
- Output
names[2] = 'Nihit'
print(names)
['Rupal', 'Pranab', 'Nihit']
Adding new items to the list
- Input
- Output
names.append('Bhanu')
print(names)
['Rupal', 'Pranab', 'Nihit', 'Bhanu']
Inserting item in a specific place.
- Input
- Output
names.insert(2, 'Nitin')
print(names)
['Rupal', 'Pranab', 'Nitin', 'Nihit', 'Bhanu']
Deleting items from list.
- Input
- Output
del names[1]
print(names)
['Rupal', 'Nitin', 'Nihit', 'Bhanu']
pop
method of removing. pop
let you use the removed item.
- Input
- Output
removed_name = names.pop() # catch the removed item
print(names)
print(removed_name)
['Rupal', 'Nitin', 'Nihit']
Bhanu
pop
can remove actually any item.
- Input
- Output
names.pop(1)
print(names)
'Nitin'
['Rupal', 'Nihit']
Remove an item by its value.
- Input
- Output
names.remove('Rupal')
print(names)
['Nihit']
If there are more than one item with same value, the .remove
method removes
only the first occurrence.
- Input
- Output
names.append('Rupal')
names.append('Nitin')
names.append('Nihit')
names.append('Bhanu')
print(names)
['Nihit', 'Rupal', 'Nitin', 'Nihit', 'Bhanu']
- Input
- Output
names.remove('Nihit')
print(names)
['Rupal', 'Nitin', 'Nihit', 'Bhanu']
Sort lists using sorted
function (it does not change the original list).
- Input
- Output
print(sorted(names))
['Bhanu', 'Nihit', 'Nitin', 'Rupal']
Sort lists permanently by using sort
method.
- Input
- Output
names.sort()
print(names)
['Bhanu', 'Nihit', 'Nitin', 'Rupal']
Reverse list times using .reverse
method
- Input
- Output
names.reverse()
print(names)
['Rupal', 'Nitin', 'Nihit', 'Bhanu']
- Input
- Output
names[2] = 'nihit'
names.sort()
print(names)
['Bhanu', 'Nitin', 'Rupal', 'nihit']
Beware of mixing uppercase and lowercase letters. The methods may not work as you might expect as shown above. While comparing strings, the ASCII values of the corresponding characters are compared. For example, ASCII code of uppercase "A" is 65 while the lowercase "a" is 97.
Looping through items of a list:
- Input
- Output
for name in names:
print(name)
Nitin
Rupal
nihit
Lists in python being mutable objects, when we set a list variable to another new variable, a new list is not created rather the new variable point to the same list.
a = [ 2, 3, 4]
b = a
b[2] = 10
print(a) # [2, 3, 10] printed
If we need to clone the list to a new variable, we can use b = a.copy()
instead. Alternatively, we can instantiate a new list form the old list
b = list(a)
.
Be also careful when passing a list as argument to a function. It will modify the existing list, rather than working in a copy to the list.
list = [2, 3, 4]
def factor(list, factor):
for i in range(len(list)):
list[i] *= factor
# return list # if we return list here, it will point to the same `list` in
# in the main function
factor(list, 2) # we passed `list` to a function which does not return anything
print(list) # [4, 6, 8]
Use range
function to create numerical lists.
- Input
- Output
nums = list(range(1, 11))
print(nums)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- Input
- Output
squares = []
for num in nums:
squares.append(num**2)
for ii in range(len(nums)):
print(nums[ii], '\t', squares[ii])
nums squares
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
- Input
- Output
even_numbers = list(range(2, 11, 2))
print(even_numbers)
[2, 4, 6, 8, 10]
List comprehensions:
- Input
- Output
squares = [value**2 for value in range(1, 11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Python lists are dynamic arrays. When a list of length n
is created, the
memory allocator allocates more than n
contiguous locations for the list.
There are some advantages doing this, such as, no need to create new list
allocation and copy items when adding new items (expanding the list size) to the
end. Also inserting in the middle just requires shifting. With static array,
whenever size increases, we need reallocation. However, we do not know how large
the array will grow, and the extra space allocated during the creation might not
be enough, in that case we need reallocation (again keeping some extra room).
One drawback is that Python might allocate more memory than we actually need.
Tuples
Tuples are just like lists except that they are immutable. However, we can update the whole tuple instead of individual entries. Here we use parenthesis instead of square bracket to define tuples.
- Input
- Output
tup = (1, 2, 3)
tup[0]
1
Reassigning values would result in errors
- Input
- Output
tup[1] = 4 # would result in error
TypeError: 'tuple' object does not support item assignment
But we can reassign the whole tuple:
- Input
- Output
tup = (2, 3, 4, 5)
print(tup)
(2, 3, 4, 5)
A single element tuple is declared by tup = (4,)
. The reason for this
requirement is that without the trailing comma, the expression (4)
is
interpreted as a simple parenthesized numeric expression.
Dictionary
Python dictionary are list of key value pairs.
- Input
- Output
my_dict = {'Pranab' : 185, 'Sasha' : 196};
print(my_dict)
{'Pranab': 185, 'Sasha': 196}
You can get values by using it's key:
- Input
- Output
my_dict['Pranab']
185
Adding new items to the dictionary:
- Input
- Output
my_dict['Luis'] = 190;
print(my_dict)
{'Pranab': 185, 'Sasha': 196, 'Luis': 190}
Reassign values:
- Input
- Output
my_dict['Luis'] = 191;
print(my_dict)
{'Pranab': 185, 'Sasha': 196, 'Luis': 191}
Delete an entry:
- Input
- Output
del my_dict['Luis'];
print(my_dict)
{'Pranab': 185, 'Sasha': 196}
Looping through keys and values in a dictionary:
- Input
- Output
print('Name\t Height');
for key, value in my_dict.items():
print(key, '\t', value);
Name Height
Pranab 185
Sasha 196
Looping through keys:
- Input
- Output
for key in my_dict.keys():
print(key, my_dict[key])
Pranab 185
Sasha 196
- Input
- Output
if 'Pranab' in my_dict.keys():
print('Hello Pranab, your height is :', my_dict['Pranab'])
Hello Pranab, your height is : 185
Similarly we can loop through values also:
- Input
- Output
my_dict.values()
dict_values([185, 196])
- Input
- Output
for value in my_dict.values():
print(value)
185
196
We can place a comma after the last item in a python list, tuple, or dictionary. It could be preferable coding style:
name = [
"Bhanu",
"Nihit",
"Rupal",
]
Sets
Sets are hash lists. To lookup a member in a hash list has complexity, whereas lookups in a python list has (n is the length of list).
s = set()
s.add(2)
s.add(4)
s.add(4) # set cannot have duplicate items
print(s) # {2, 4} printed
s.remove(2) # s.discard(2), if element is absent remove method will raise error
4 in s # True
Set can also be initialized by following way:
s = set({2, 4})
list = (3, 4, 5)
s2 = set(list)
arr = [5, 6]
s3 = set(arr)
Size of set:
len(s) # 2
Union:
s4 = s | s2 # {2, 3, 4, 5}
# or
s4 = s.union(s2)
Intersection:
s5 = s & s2 # {3}
Difference:
s5 = s.difference(s2) # {2}
# or
s5 = s - s2
More methods:
s.isdisjoint(s2)
s.issubset(s2)
s.issuperset(s2)
We can create immutable set by:
sf = frozenset({2, 3, 4})