Skip to main content

List, tuple, and dictionary

List

It is a good idea to name lists as plural as they contain multiple elements. Like, names, items etc.

names = ['Rupal', 'Pranab', 'Bhanu']
print(names)

Lists are mutable, we can change its contents:

names[2] = 'Nihit'
print(names)

Adding new items to the list

names.append('Bhanu')
print(names)

Inserting item in a specific place.

names.insert(2, 'Nitin')
print(names)

Deleting items from list.

del names[1]
print(names)

pop method of removing. pop let you use the removed item.

removed_name = names.pop()  # catch the removed item
print(names)
print(removed_name)

pop can remove actually any item.

names.pop(1)
print(names)

Remove an item by its value.

names.remove('Rupal')
print(names)
note

If there are more than one item with same value, the .remove method removes only the first occurrence.

names.append('Rupal')
names.append('Nitin')
names.append('Nihit')
names.append('Bhanu')
print(names)
names.remove('Nihit')
print(names)

Sort lists using sorted function (it does not change the original list).

print(sorted(names))

Sort lists permanently by using sort method.

names.sort()
print(names)

Reverse list times using .reverse method

names.reverse()
print(names)
names[2] = 'nihit'
names.sort()
print(names)
caution

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:

for name in names:
print(name)
info

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.

nums = list(range(1, 11))
print(nums)
squares = []
for num in nums:
squares.append(num**2)

for ii in range(len(nums)):
print(nums[ii], '\t', squares[ii])
even_numbers = list(range(2, 11, 2))
print(even_numbers)

List comprehensions:

squares = [value**2 for value in range(1, 11)]
print(squares)
note

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.

tup = (1, 2, 3)
tup[0]

Reassigning values would result in errors

tup[1] = 4 # would result in error

But we can reassign the whole tuple:

tup = (2, 3, 4, 5)
print(tup)
info

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.

my_dict = {'Pranab' : 185, 'Sasha' : 196};
print(my_dict)

You can get values by using it's key:

my_dict['Pranab']

Adding new items to the dictionary:

my_dict['Luis'] = 190;
print(my_dict)

Reassign values:

my_dict['Luis'] = 191;
print(my_dict)

Delete an entry:

del my_dict['Luis'];
print(my_dict)

Looping through keys and values in a dictionary:

print('Name\t Height');
for key, value in my_dict.items():
print(key, '\t', value);

Looping through keys:

for key in my_dict.keys():
print(key, my_dict[key])
if 'Pranab' in my_dict.keys():
print('Hello Pranab, your height is :', my_dict['Pranab'])

Similarly we can loop through values also:

my_dict.values()
for value in my_dict.values():
print(value)
tip

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 O(1)O(1) complexity, whereas lookups in a python list has O(n)O(n) (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})