Variable and Data Types

Python tutorial · PySpark.in

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.

```

student_name = "Mary"

student_name = "John" # changed value

count = 5

count = count + 1 # count becomes 6

count = 10 # count changes again

print(student_name)

print(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:

```

x, y, z = 10, 20, 30

print(x, y, z) # 10 20 30

```

You can also assign the same value to multiple variables:

```

a = b = c = 5

print(a, b, c) # 5 5 5

```

Python is Dynamically Typed

Python determines it automatically based on the assigned value.

```

x = 10 # int

x = "Hello" # str (same variable, new type)

```

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).

```

a = 5

b = -10

c = 0

print(type(a))

```

2. Floating Point Numbers (float)

Numbers with decimal points.

```

x = 3.14

y = -2.5

z = 1.5e3 # 1.5 × 10³ = 1500.0

print(type(x))

```

3. Strings (str)

Text enclosed in single, double, or triple quotes.

```

name = "Python"

message = 'Hello World!'

multiline = """This is

a multi-line string."""

print(name, type(name))

```

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

4. Boolean (bool)

Represents logical values — True or False.

```

x = True

y = False

print(10 > 5) # True

print(type(x))

```

5. NoneType (None)

Represents the absence of a value.

```

x = None

print(x, type(x))

```

Python Collection (Container) Data Types

List

Ordered, mutable, allows duplicates.

```

fruits = ["apple", "banana", "cherry"]

fruits.append("orange")

print(fruits)

```

Tuple

Ordered, immutable, allows duplicates.

```

colors = ("red", "green", "blue")

print(colors[1])

```

Set

Unordered, no duplicates, mutable.

```

numbers = {1, 2, 3, 3, 4}

numbers.add(5)

print(numbers)

```

Dictionary (dict)

Stores key-value pairs, mutable, unordered.

```

student = {"name": "Rohan", "age": 21, "course": "BTech"}

print(student["name"])

student["age"] = 23

print(student)

```

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.

```

x = 10 # int

y = float(x) # 10.0

z = str(x) # '10'

print(y, type(y))

print(z, type(z))

```

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)

```

numbers = [1, 2, 3]

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

numbers.append(4)

print(numbers) # [1, 2, 3, 4]

print(id(numbers)) # Same memory address (object changed)

```

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

```

name = name + "3.12"

print(name) # "Python3.12"

print(id(name)) # Different memory address (new object created)

```

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