Skip to content

Latest commit

 

History

History
1043 lines (780 loc) · 14.7 KB

list-tuple-dict.mdx

File metadata and controls

1043 lines (780 loc) · 14.7 KB
title sidebar_label
List, tuple, and dictionary
List, tuple, dictionary

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

List

It is a good idea to name lists as plural as they contain multiple elements. Like, names, items etc. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

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

Lists are mutable, we can change its contents: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names[2] = 'Nihit'
print(names)
['Rupal', 'Pranab', 'Nihit']

Adding new items to the list <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.append('Bhanu')
print(names)
['Rupal', 'Pranab', 'Nihit', 'Bhanu']

Inserting item in a specific place. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.insert(2, 'Nitin')
print(names)
['Rupal', 'Pranab', 'Nitin', 'Nihit', 'Bhanu']

Deleting items from list. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

del names[1]
print(names)
['Rupal', 'Nitin', 'Nihit', 'Bhanu']

pop method of removing. pop let you use the removed item. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

removed_name = names.pop()  # catch the removed item
print(names)
print(removed_name)
['Rupal', 'Nitin', 'Nihit']
Bhanu

pop can remove actually any item. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.pop(1)
print(names)
'Nitin'
['Rupal', 'Nihit']

Remove an item by its value. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.remove('Rupal')
print(names)
['Nihit']

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

<Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.append('Rupal')
names.append('Nitin')
names.append('Nihit')
names.append('Bhanu')
print(names)
['Nihit', 'Rupal', 'Nitin', 'Nihit', 'Bhanu']

<Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.remove('Nihit')
print(names)
['Rupal', 'Nitin', 'Nihit', 'Bhanu']

Sort lists using sorted function (it does not change the original list). <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

print(sorted(names))
['Bhanu', 'Nihit', 'Nitin', 'Rupal']

Sort lists permanently by using sort method. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.sort()
print(names)
['Bhanu', 'Nihit', 'Nitin', 'Rupal']

Reverse list times using .reverse method <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names.reverse()
print(names)
['Rupal', 'Nitin', 'Nihit', 'Bhanu']

<Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

names[2] = 'nihit'
names.sort()
print(names)
['Bhanu', 'Nitin', 'Rupal', 'nihit']

:::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: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

for name in names:
    print(name)
Nitin
Rupal
nihit

:::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. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

nums = list(range(1, 11))
print(nums)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

<Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: '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

<Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

even_numbers = list(range(2, 11, 2))
print(even_numbers)
[2, 4, 6, 8, 10]

List comprehensions: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

squares = [value**2 for value in range(1, 11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

:::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. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

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

Reassigning values would result in errors <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

tup[1] = 4 # would result in error
TypeError: 'tuple' object does not support item assignment

But we can reassign the whole tuple: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

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

:::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. <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

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

You can get values by using it's key: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

my_dict['Pranab']
185

Adding new items to the dictionary: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

my_dict['Luis'] = 190;
print(my_dict)
{'Pranab': 185, 'Sasha': 196, 'Luis': 190}

Reassign values: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

my_dict['Luis'] = 191;
print(my_dict)
{'Pranab': 185, 'Sasha': 196, 'Luis': 191}

Delete an entry: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

del my_dict['Luis'];
print(my_dict)
{'Pranab': 185, 'Sasha': 196}

Looping through keys and values in a dictionary: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: '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: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

for key in my_dict.keys():
    print(key, my_dict[key])
Pranab 185
Sasha 196

<Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: '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: <Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

my_dict.values()
dict_values([185, 196])

<Tabs defaultValue="input" values={[ { label: 'Input', value: 'input', }, { label: 'Output', value: 'output', }, ] }>

for value in my_dict.values():
    print(value)
185
196

:::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)$ complexity, whereas lookups in a python list has $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})