1. For Loop with Index (C-style)
Java:
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index: " + i + ", Value: " + numbers[i]);
}
Python:
numbers = [10, 20, 30, 40, 50]
for i in range(len(numbers)):
print(f"Index: {i}, Value: {numbers[i]}")
Key Differences:
- Java uses explicit index counter
i. - Python uses
range(len(list))to generate indices. range()generates a sequence of numbers.
2. Enhanced For Loop (For-Each)
Java:
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
Python:
numbers = [10, 20, 30, 40, 50]
for num in numbers:
print(num)
Comparison:
- Both iterate over elements directly without needing indices.
- Python's syntax is simpler (no type declaration needed).
- This is the most Pythonic way to iterate.
3. While Loop
Java:
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
Python:
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
Characteristics:
- Both continue until the condition becomes false.
- Similar syntax and behavior.
4. Do-While Loop
Java:
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);
Python:
# Python doesn't have do-while; simulate with while + break
count = 0
while True:
print(f"Count: {count}")
count += 1
if count >= 5:
break
Key Difference:
- Java has native
do-while. - Python achieves this with
while True+ conditionalbreak.
5. Iterating Over Strings
Java:
String text = "Hello";
for (char c : text.toCharArray()) {
System.out.println(c);
}
// Or with index
for (int i = 0; i < text.length(); i++) {
System.out.println(text.charAt(i));
}
Python:
text = "Hello"
for c in text:
print(c)
# With index
for i, c in enumerate(text):
print(f"Index: {i}, Character: {c}")
Key Feature:
- Python's
enumerate()provides both index and value.
6. Iterating Over Collections (Lists, Sets, Dicts)
Lists
Java:
ArrayList<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "orange"));
for (String fruit : fruits) {
System.out.println(fruit);
}
Python:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
Sets
Java:
Set<Integer> numbers = new HashSet<>(Arrays.asList(10, 20, 30));
for (int num : numbers) {
System.out.println(num);
}
Python:
numbers = {10, 20, 30}
for num in numbers:
print(num)
Dictionaries
Java:
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
// Iterate over keys
for (String name : ages.keySet()) {
System.out.println(name);
}
// Iterate over values
for (int age : ages.values()) {
System.out.println(age);
}
// Iterate over key-value pairs
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Python:
ages = {"Alice": 25, "Bob": 30}
# Iterate over keys
for name in ages:
print(name)
# Iterate over values
for age in ages.values():
print(age)
# Iterate over key-value pairs
for name, age in ages.items():
print(f"{name}: {age}")
7. Break and Continue
Java:
for (int i = 0; i < 10; i++) {
if (i == 3) {
continue; // Skip this iteration
}
if (i == 7) {
break; // Exit loop
}
System.out.println(i);
}
Python:
for i in range(10):
if i == 3:
continue # Skip this iteration
if i == 7:
break # Exit loop
print(i)
Output (both):
0
1
2
4
5
6
8. Nested Loops
Java:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
Python:
for i in range(1, 4):
for j in range(1, 4):
print(f"i: {i}, j: {j}")
9. Enumerate (Python-Specific)
Python Only:
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: orange
# With custom starting index
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")
Java Equivalent (more verbose):
ArrayList<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "orange"));
for (int i = 0; i < fruits.size(); i++) {
System.out.println(i + ": " + fruits.get(i));
}
10. Zip (Python-Specific)
Python Only:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# Output:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old
Java Equivalent:
ArrayList<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
ArrayList<Integer> ages = new ArrayList<>(Arrays.asList(25, 30, 35));
for (int i = 0; i < names.size(); i++) {
System.out.println(names.get(i) + " is " + ages.get(i) + " years old");
}
11. List Comprehension (Python-Specific)
Python Only:
# Instead of looping to build a list
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Java Equivalent (more verbose):
List<Integer> squares = new ArrayList<>();
for (int x = 0; x < 10; x++) {
squares.add(x * x);
}
// Or with Streams
List<Integer> squaresStream = IntStream.range(0, 10)
.map(x -> x * x)
.boxed()
.collect(Collectors.toList());
12. Range Usage in Python
Python:
# range(stop)
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop)
for i in range(2, 7):
print(i) # 2, 3, 4, 5, 6
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Reverse
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1
13. Practical Examples
Example 1: Sum All Elements
Java:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println(sum); // 15
Python:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # 15
# Or manually
total = 0
for num in numbers:
total += num
print(total) # 15
Example 2: Filter and Transform
Java:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> result = new ArrayList<>();
for (int num : numbers) {
if (num % 2 == 0) {
result.add(num * 2);
}
}
System.out.println(result); // [4, 8, 12]
Python:
numbers = [1, 2, 3, 4, 5, 6]
result = [num * 2 for num in numbers if num % 2 == 0]
print(result) # [4, 8, 12]
# Or traditional
result = []
for num in numbers:
if num % 2 == 0:
result.append(num * 2)
print(result) # [4, 8, 12]
Example 3: Process Tuples
Java:
List<Map.Entry<String, Integer>> pairs = Arrays.asList(
new AbstractMap.SimpleEntry<>("Alice", 25),
new AbstractMap.SimpleEntry<>("Bob", 30)
);
for (Map.Entry<String, Integer> entry : pairs) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Python:
pairs = [("Alice", 25), ("Bob", 30)]
for name, age in pairs:
print(f"{name}: {age}")
Summary Table
-
Index-based For
- Java Syntax:
for(int i=0; i<n; i++) - Python Syntax:
for i in range(n): - Notes: Traditional C-style
- Java Syntax:
-
For-Each
- Java Syntax:
for(T x : collection) - Python Syntax:
for x in collection: - Notes: Most Pythonic/idiomatic
- Java Syntax:
-
While
- Java Syntax:
while (condition) - Python Syntax:
while condition: - Notes: Similar behavior
- Java Syntax:
-
Do-While
- Java Syntax:
do { } while(condition) - Python Syntax: Not available natively
- Notes: Use
while True + break
- Java Syntax:
-
With Index & Value
- Java Syntax: Manual tracking
- Python Syntax:
for i, x in enumerate() - Notes: Python's
enumerate()is more elegant
-
Multiple Variables
- Java Syntax: Not straightforward
- Python Syntax:
for x, y in zip() - Notes: Python's
zip()is powerful
-
List Building
- Java Syntax: Streams (verbose)
- Python Syntax: List comprehension
- Notes: Python is more concise
-
Break/Continue
- Java Syntax:
break/continue - Python Syntax:
break/continue - Notes: Same behavior
- Java Syntax: