Python Language Basics

🐍 Python Collection Data Types

⚖️ Quick Comparison Table

TypeOrderedMutableUniqueIndexableDuplicates AllowedNotable Use Case
listGeneral-purpose sequence
tupleFixed-size data
setUnique elements, set operations
frozensetImmutable set
dict✅ (keys)✅ (by key)✅ (values only)Key-value pairs
dequeLimited (0, -1)Fast double-ended queue
namedtuple✅, attr accessTuple with field names
defaultdict✅ (keys)✅ (by key)✅ (values only)Dict with auto-init for missing keys
Counter✅ (keys)✅ (by key)✅ (values count duplicates)Counting/frequency of elements

🔹 dict keys must be unique
🔹 Tuples can be used as dict keys if they’re hashtable (no lists inside)

Immutable Data Types Table

TypeDescriptionExample
intInteger numbersx = 10
floatFloating-point numbersx = 3.14
boolBoolean valuesx = True
strString (sequence of characters)x = "hello"
tupleImmutable ordered sequencex = (1, 2, 3)
frozensetImmutable setx = frozenset([1, 2, 3])
bytesImmutable byte sequencex = b'data'
complexComplex numbersx = 2 + 3j
NoneTypeRepresents 'no value'x = None

Collection Operations Time Complexity(BigO) Table

CollectionOperationTime ComplexityExample
listIndexingO(1)x = lst[2]
listAppendO(1) amortizedlst.append(10)
listInsert (start/middle)O(n)lst.insert(1, 99)
listPop (end)O(1)x = lst.pop()
listPop (start)O(n)x = lst.pop(0)
listRemove by valueO(n)lst.remove(10)
listMembership testO(n)if 5 in lst: pass
listIterationO(n)for x in lst: pass
listSortO(n log n)lst.sort()
listSlicingO(k)sub = lst[1:4]
tupleIndexingO(1)x = tpl[1]
tupleMembership testO(n)if 3 in tpl: pass
tupleIterationO(n)for x in tpl: pass
tupleConcatenationO(n + m)tpl3 = tpl1 + tpl2
tupleSlicingO(k)sub = tpl[1:3]
setAddO(1)s.add(5)
setRemoveO(1)s.remove(5)
setMembership testO(1)if 5 in s: pass
setIterationO(n)for x in s: pass
frozensetMembership testO(1)if 2 in fs: pass
frozensetIterationO(n)for x in fs: pass
dictGetO(1)x = d['key']
dictSetO(1)d['key'] = 10
dictDeleteO(1)del d['key']
dictMembership testO(1)if 'key' in d: pass
dictIterationO(n)for k, v in d.items(): pass

📦 1. list

  • ✅ Mutable
  • ✅ Ordered
  • ❌ Not Unique
  • ✅ Indexable
  • ✅ Duplicates allowed

Use case: Dynamic, ordered collections with duplicates.

my_list = [1, 2, 3, 4]
my_list.append(4)
my_list.insert(0, 0)
my_list[0] = 10

🔒 2. tuple

  • ❌ Immutable
  • ✅ Ordered
  • ❌ Not Unique
  • ✅ Indexable
  • ✅ Duplicates allowed

Use case: Fixed-size data, coordinates, function return values.

position = (10, 20)
# position[0] = 5  # ❌ Error

🧺 3. set

  • ✅ Mutable
  • ❌ Unordered
  • ✅ Unique
  • ❌ Indexable
  • ❌ Duplicates not allowed

Use case: Unordered collections with no duplicates, set operations.

unique_items = {1, 2, 3}
unique_items.add(4)
unique_items.discard(2)

🧭 4. dict

  • ✅ Mutable
  • ✅ Ordered (Python 3.7+)
  • ✅ Unique keys
  • ✅ Key-based access
  • ✅ Duplicates allowed for values

Use case: Fast key-value lookup, structured data.

person = {"name": "Alice", "age": 30}
person["age"] = 31

🧊 5. frozenset

  • ❌ Immutable
  • ❌ Unordered
  • ✅ Unique
  • ❌ Indexable
  • ❌ Duplicates not allowed

Use case: Hashtable version of set, usable as dict or set key.

fset = frozenset([1, 2, 3])
# fset.add(4)  # ❌ Error

📚 6. collections.deque

  • ✅ Mutable
  • ✅ Ordered
  • ❌ Not Unique
  • ✅ Indexable (partial)
  • ✅ Duplicates allowed

Use case: Fast appends/pops from both ends (queue/stack).

from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.pop()

📊 7. collections.namedtuple

  • ❌ Immutable
  • ✅ Ordered
  • ❌ Unique not enforced
  • ✅ Indexable and attribute access

Use case: Tuple with named fields, lightweight class alternative.

from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(10, 20)
print(p.x, p[1])

📐 8. collections.defaultdict

  • ✅ Mutable
  • ✅ Ordered (Python 3.7+)
  • ✅ Unique keys
  • ✅ Key-based access

Use case: Dict with default factory (no KeyError on missing keys).

from collections import defaultdict
d = defaultdict(int)
d["a"] += 1

🔁 9. collections.Counter

  • ✅ Mutable
  • ✅ Ordered (in output)
  • ✅ Unique keys
  • ✅ Key-based access

Use case: Count frequency of items (e.g., words, characters).

from collections import Counter
c = Counter("banana")
print(c["a"])  # 3

Exercises

NamedTuple

from typing import NamedTuple

class Point(NamedTuple):
    x: float
    y: float

p = Point(1.5, 2.5)
print(p.x, p.y)       # 1.5 2.5
print(p[0], p[1])     # 1.5 2.5
class Color(NamedTuple):
    red: int
    green: int
    blue: int

white = Color(255, 255, 255)
print(white.red)  # 255
class ApiResponse(NamedTuple):
    status_code: int
    message: str
    data: dict

res = ApiResponse(200, "OK", {"user": "kenan"})
print(res.status_code, res.data["user"])  # 200 kenan

Tuples

A tuple is a collection which is ordered and unchangeable or immutable.




Continue reading

JavaScript ES6 Classes and Arrow Functions

I try to understand difference between function expression, shorthand method definition, arrow function and bind().

Notice that I defined sayGoodBye() function in constructor, it means that whenever i create a new instance from this Person class, sayGoodBye() function will be defined for every instance.

sayHello() function is defined as a class property. But, as you can see in the following screenshot, class properties are also defined in constructor so class properties are just a sugar syntax.

getFullName() function is defined as shorthand method definition. But, Babel didn't move function definition in class constructor. So, if we use shorthand method definition in class, it will be a prototype function .

It mean they are only defined once, instead of once per instance.

Notice that in below screenshot, getFullName() function is in prototype of Person class, but sayHello() and sayGoodBye() are not.

Continue reading

JavaScript Three Ways of Handling Asynchronous Operations

There is one more post about Promise and Async/Await usage in the following link.

There are 3 ways to handle asynchronous function calls.

Using Callbacks

Continue reading

Node.js Mocha and Chai

Mocha is a test framework to run tests.

https://mochajs.org/#assertions

Chai is an assertion library and you can find full documentation in the following link.

https://www.chaijs.com/api/bdd/

There are three type of assertion libraries in Chai.

  • Expect
  • Should
  • Assert

expect and should use the same chainable language to construct assertions.

Assume that expect library is used like below

expect(firstName).to.be.a('string');
expect(firstName).to.equal('kenan');
expect(firstName).to.have.lengthOf(5);
expect(beverages).to.have.property('tea').with.lengthOf(3);

Above code could be written with should library like below.

firstName.should.be.a('string');
firstName.should.equal('kenan');
firstName.should.have.lengthOf(5);
beverages.should.have.property('tea').with.lengthOf(3);

You can find more detailed usage with Express, Mocha and Chai in the following repository

https://github.com/nodejs-projects-kenanhancer/express-demo.git

Continue reading

Find Interaction Algorithm

FindIntersection(strArr) read the array of strings stored in strArr which will contain 2 elements: the first element will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers (also sorted). Your goal is to return a comma-separated string containing the numbers that occur in elements of strArr in sorted order. If there is no intersection, return the string false

Demo 1

Continue reading