Variable and Data Types

Python tutorial · PySpark.in

Variable and Data Types

Variable

A variable is a name that refers to a memory location where a value is stored.

Assigning Values to Variables

Use the assignment operator (=) to store a value in a variable.

PYTHON
1student_name = "Mary"
2student_name = "John" # changed value
3count = 5
4count = count + 1 # count becomes 6
5count = 10 # count changes again
6print(student_name)
7print(count)
▶ 

Rules for Naming Variables

Rule

Example

Can contain letters (A–Z, a–z), digits (0–9), and underscores (_)

Allowed student_name

Cannot start with a digit

Not allowed 1student

Cannot contain spaces

Not allowed student name

Cannot use special characters (except _)

Not allowed student@name

Cannot use hyphens (-)

Not allowed student-name

Variable names are case-sensitive

Name ≠ name

Avoid leading/trailing underscores unless needed

Reserved patterns in Python.

Naming Conventions

Convention

Example

Used For

snake_case

student_name

Common in Python

camelCase

studentName

Used by some developers

UPPER_CASE

PI = 3.14

Used for constants

Multiple Assignments

Python allows you to assign multiple variables in one line:

PYTHON
1x, y, z = 10, 20, 30
2print(x, y, z) # 10 20 30
▶ Output will appear here.

You can also assign the same value to multiple variables:

PYTHON
1a = b = c = 5
2print(a, b, c) # 5 5 5
▶ Output will appear here.

Python is Dynamically Typed

Python determines it automatically based on the assigned value.

```
x = 10      # int
x = "Hello"  # str (same variable, new type)
print(x)

```

Python Data Types

Data types define the kind of value a variable can hold.

Basic (Primitive) Data Types

1. Integers (int)

Whole numbers (positive or negative).

PYTHON
1a = 5
2b = -10
3c = 0
4print(type(a))
▶ Output will appear here.

2. Floating Point Numbers (float)

Numbers with decimal points.

PYTHON
1x = 3.14
2y = -2.5
3z = 1.5e3 # 1.5 × 10³ = 1500.0
4print(type(x))
▶ Output will appear here.

3. Strings (str)

Text enclosed in single, double, or triple quotes.

PYTHON
1name = "Python"
2message = 'Hello World!'
3multiline = """This is
4a multi-line string."""
5print(name, type(name))
▶ Output will appear here.

Strings are immutable and support slicing, concatenation, and built-in methods like .upper(), .lower(), .replace().

4. Boolean (bool)

Represents logical values — True or False.

PYTHON
1x = True
2y = False
3print(10 > 5) # True
4print(type(x))
▶ Output will appear here.

5. NoneType (None)

Represents the absence of a value.

PYTHON
1x = None
2print(x, type(x))
▶ Output will appear here.

Python Collection (Container) Data Types

List

Ordered, mutable, allows duplicates.

PYTHON
1fruits = ["apple", "banana", "cherry"]
2fruits.append("orange")
3print(fruits)
▶ Output will appear here.
  • Access by index: fruits[0] → 'apple'
  • Supports slicing: fruits[1:3] → ['banana', 'cherry']

Tuple

Ordered, immutable, allows duplicates.

PYTHON
1colors = ("red", "green", "blue")
2print(colors[1])
▶ Output will appear here.

Set

Unordered, no duplicates, mutable.

PYTHON
1numbers = {1, 2, 3, 3, 4}
2numbers.add(5)
3print(numbers)
▶ Output will appear here.

Dictionary (dict)

Stores key-value pairs, mutable, unordered.

PYTHON
1student = {"name": "Rohan", "age": 21, "course": "BTech"}
2print(student["name"])
3student["age"] = 23
4print(student)
▶ Output will appear here.

Data Types

Type

Description

Example

range

Sequence of numbers

range(1, 6) → [1,2,3,4,5]

bytes

Immutable binary data

b = b"Hello"

bytearray

Mutable binary data

bytearray(b"Hi")

memoryview

View/edit binary data without copying

memoryview(bytearray(b"Python"))

frozenset

Immutable set

frozenset({1, 2, 3})

array (module)

Efficient numeric array

from array import array

Type Conversion (Casting)

Convert one data type to another using functions like int(), float(), str(), list(), etc.

PYTHON
1x = 10 # int
2y = float(x) # 10.0
3z = str(x) # '10'
4print(y, type(y))
5print(z, type(z))
▶ Output will appear here.

Difference Between Mutable and Immutable Objects

Feature

Mutable Objects

Immutable Objects

Definition

Can be changed after creation

Cannot be changed after creation

Memory Address

Remains same even after modification

Changes when a new value is assigned

Examples

List, Dictionary, Set, bytearray

int, float, string, tuple, frozenset, bytes

Can Add / Remove Elements

Yes

No

Performance

Slightly slower (extra memory for flexibility)

Faster (no modification tracking)

Use Case

When data needs to change (e.g., dynamic lists)

When data must remain constant (e.g., keys in dicts)

Example of a Mutable Object (List)

PYTHON
1numbers = [1, 2, 3]
2print(id(numbers)) # Memory address before change
3numbers.append(4)
4print(numbers) # [1, 2, 3, 4]
5print(id(numbers)) # Same memory address (object changed)
▶ Output will appear here.

The same list object was modified — so list is mutable.

Example of an Immutable Object (String)

name = "Python"

print(id(name)) # Memory address before change

PYTHON
1name = name + "3.12"
2print(name) # "Python3.12"
3print(id(name)) # Different memory address (new object created)
▶ Output will appear here.

The old string wasn’t modified — instead, Python created a new string in memory.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges