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)

📦 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

How to install Python with pyenv version manager

I am using different programming languages like C#, Java, Node.js etc and need to manage runtime versions in my local. So, I like to use runtime version managers.

For example, there are some runtime version managers in Node.js community like nvm or n.

Let's say I work for one Node.js project in dev machine with Node v8.0.0 but other project needs Node v6.0.0

In order to handle, different versions in same machine, we may use runtime version managers.

I just want to find a way to switch between different Python runtime version so that found pyenv runtime version manager.

Pyenv is a simple, powerful and cross-platform tool for managing multiple versions of Python on a single machine. It is very useful when you need to switch between different Python versions for different projects, or when different applications on your system require different Python versions.

So, we can install, uninstall, list or switch between different versions.

Pyenv installation

Click pyenv link for more detailed installation.

Installing pyenv with Homebrew

First, ensure that you have Homebrew installed in your system. Homebrew is a package manager for Mac OS. So if you want to learn more details about it, visit my post.

Run the following commands in your terminal. But, just copy commands without $ sign.

$ brew update
$ brew install pyenv

Setting PATH

Checking shell

output of echo $SHELL can be bash, zsh or fish

$ echo $SHELL

/usr/local/bin/bash

# OR

/bin/zsh

Run the following command for bash, zsh, etc configuration.

$ echo 'eval "$(pyenv init -)"' >> ~/.zshrc

and restart your terminal manually or run the following command to restart automatically.

$ exec "$SHELL"

Upgrading pyenv

$ brew upgrade pyenv

Uninstall pyenv

$ rm -rf $(pyenv root)
$ brew uninstall pyenv

Pyenv commands

List all Python versions installed in system

$ pyenv versions

  system
  3.7.3
* 3.8.2 (set by /Users/kenanhancer/.pyenv/version)

Show current active Python version in system

$ pyenv version

3.8.2 (set by /Users/kenanhancer/.pyenv/version)
Continue reading