Back to Programming

Python

Python for Beginners – Variables, Lists and Loops

Quick introduction to variables, basic data types, lists and for/while loops in Python.

1. Variables and Data Types

Python is dynamically typed, meaning you don't need to declare variable types explicitly. The type is determined automatically based on the value assigned. This makes Python code more concise and easier to write, though it requires careful attention to ensure correct types are used.

Python's dynamic typing allows variables to change types during execution, which provides flexibility but can also lead to errors if not managed carefully. Understanding Python's type system helps write robust code and avoid common type-related bugs.

Common Data Types

  • int – Integers (whole numbers). Can be arbitrarily large in Python 3. Examples: 10, -5, 0, 1000000
  • float – Floating-point numbers (decimals). Examples: 3.14, -2.5, 0.0, 1e10
  • bool – Boolean values. Only two values: True and False. Used in conditional statements and logical operations.
  • str – Strings (text). Can use single, double, or triple quotes. Examples: "Hello", 'World', """Multi-line string"""
  • list – Ordered, mutable collections. Can contain mixed types. Examples: [1, 2, 3], ['a', 'b', 'c'], [1, 'hello', 3.14]
  • tuple – Ordered, immutable collections. Faster than lists, used for fixed data. Examples: (1, 2, 3), ('a', 'b')
  • dict – Key-value pairs (dictionaries). Unordered, mutable. Examples: {'name': 'John', 'age': 25}

2. Lists

Lists are ordered, mutable collections that can contain elements of different types. They are one of Python's most versatile and commonly used data structures. Lists support indexing, slicing, and various methods for manipulation.

Lists are zero-indexed (first element is at index 0) and support negative indexing (last element is at index -1). They can grow or shrink dynamically, making them ideal for many programming tasks.

List Operations


# Creating lists
numbers = [10, 20, 30]
mixed = [1, 'hello', 3.14, True]
empty = []

# Accessing elements
print(numbers[0])    # 10 (first element)
print(numbers[-1])   # 30 (last element)

# Modifying lists
numbers.append(40)   # Add to end
numbers.insert(1, 15) # Insert at index
numbers[0] = 5       # Modify element

# List methods
numbers.remove(20)   # Remove first occurrence
numbers.pop()        # Remove and return last element
numbers.sort()       # Sort in place
numbers.reverse()    # Reverse list

# Iterating over lists
for n in numbers:
    print(n)

# List comprehension (advanced)
squares = [x**2 for x in range(10)]

Common List Operations

Operation Description Example
len() Get list length len([1,2,3]) → 3
append() Add element to end lst.append(4)
extend() Add multiple elements lst.extend([4,5])
insert() Insert at position lst.insert(0, 0)
remove() Remove first occurrence lst.remove(2)
pop() Remove and return element lst.pop()
index() Find index of element lst.index(3)
count() Count occurrences lst.count(2)
sort() Sort in place lst.sort()
reverse() Reverse list lst.reverse()

3. Loops

Loops allow you to execute code repeatedly, which is essential for processing collections of data, iterating through sequences, and implementing algorithms. Python provides two main types of loops: for loops and while loops.

For loops are preferred when you know the number of iterations or want to iterate over a sequence. While loops are used when repetition depends on a condition that may change during execution. Choosing the right loop type makes code more readable and efficient.

For Loop

The for loop iterates over a sequence (list, string, tuple, range, etc.). It's the most common loop in Python and is very readable and Pythonic.


# Iterate over list
numbers = [10, 20, 30, 40, 50]
for num in numbers:
    print(num)

# Iterate with index
for i in range(len(numbers)):
    print(f"Index {i}: {numbers[i]}")

# Iterate with enumerate (get index and value)
for index, value in enumerate(numbers):
    print(f"Index {index}: {value}")

# Iterate over string
text = "Python"
for char in text:
    print(char)

# Iterate over range
for i in range(5):        # 0 to 4
    print(i)

for i in range(1, 6):     # 1 to 5
    print(i)

for i in range(0, 10, 2): # 0 to 9, step 2
    print(i)

While Loop

The while loop repeats as long as a condition is true. It's useful when the number of iterations is unknown or depends on runtime conditions.


# Basic while loop
count = 0
while count < 5:
    print(count)
    count += 1

# While with user input
number = 0
while number != -1:
    number = int(input("Enter number (-1 to quit): "))
    print(f"You entered: {number}")

# While with break
while True:
    user_input = input("Enter command: ")
    if user_input == "quit":
        break
    print(f"Processing: {user_input}")

Loop Control Statements

  • break – Exits the loop immediately, skipping remaining iterations
  • continue – Skips the rest of the current iteration and continues with the next iteration
  • else – Executes when loop completes normally (not exited by break)

4. Practice Programs

Practice these programs to master variables, lists, and loops:

  • Sum of list elements – Iterate through a list and calculate the sum
  • Find maximum/minimum in a list – Traverse list and find largest/smallest value
  • Count positive numbers – Count how many positive numbers are in a list
  • Reverse a list – Create a reversed version of a list
  • Remove duplicates – Remove duplicate elements from a list
  • List statistics – Calculate mean, median, mode of a list
  • List filtering – Create a new list with elements that meet certain criteria
  • Nested loops – Process 2D lists or create patterns

Frequently Asked Questions

Q1: What is the difference between list and tuple in Python?

Lists are mutable (can be modified after creation) and use square brackets []. Tuples are immutable (cannot be modified) and use parentheses (). Lists are used when you need to modify the collection, tuples when you need a fixed sequence. Tuples are faster and can be used as dictionary keys.

Q2: When should I use for loop vs while loop?

Use for loops when iterating over a known sequence or when you know the number of iterations. Use while loops when repetition depends on a condition that changes during execution or when the number of iterations is unknown. For loops are generally preferred in Python for readability.

Q3: What is list comprehension and why is it useful?

List comprehension is a concise way to create lists. Syntax: [expression for item in iterable if condition]. It's more readable and often faster than traditional loops for creating lists. Example: [x**2 for x in range(10) if x % 2 == 0] creates squares of even numbers.