Variable Examples in Python
Variable Naming Rules
- Variable names should start with alphanumeric characters, an underscore (
_
), or a string. - Variable names must not start with numbers or hyphens.
- Variable names are case-sensitive.
Invalid Variable Examples
1 2 3 4 5 6 |
|
Multiple Variables
Assigning Multiple Values
1 2 |
|
Swapping Variables
Using Unpacking
1 2 3 4 |
|
O(1)
- Simply swapping references to the string objects.
- Space Complexity: O(1)
- No additional space is required.
Using Additional Memory
1 2 3 4 |
|
O(1)
- Each assignment is a constant-time operation.
- Space Complexity: O(1)
- Introduces a single additional variable c
.
Using Slicing Without Additional Memory
1 2 3 4 |
|
O(n + m)
- Where n
is the length of string a
and m
is the length of string b
.
- Space Complexity: O(n + m)
- Slicing operations create new strings.
Integer Swapping
Using Unpacking
1 2 3 4 |
|
Using Arithmetic Operations
1 2 3 4 |
|
Using XOR Approach
1 2 3 4 |
|
One Value to Multiple Variables
1 2 |
|
Unpack a Collection
List Example
1 2 3 |
|