Python Lists and Arrays


In Python, both lists and arrays can be used to store multiple items in a single variable. However, they serve slightly different purposes.


🔹 Python Lists

A list is a built-in, flexible data structure that can store any data type — integers, strings, floats, or even other lists.

my_list = [1, 2, 3, "hello", 4.5]
print(my_list)

✅ Output: [1, 2, 3, 'hello', 4.5]


🔸 List Features
  • Ordered

  • Mutable (you can change items)

  • Allows duplicates

  • Can store mixed types


🔸 Accessing List Items
print(my_list[0])     # First item
print(my_list[-1])    # Last item

🔸 Modifying Lists
my_list[1] = 99
print(my_list)  # [1, 99, 3, 'hello', 4.5]

🔸 Adding Items
my_list.append("new")   # Add at end
my_list.insert(2, "mid")  # Add at index

🔸 Removing Items
my_list.remove("hello")   # Remove by value
my_list.pop()             # Remove last item

🔹 Python Arrays

Python also has an array module, but it only stores items of the same type (like all integers).

import array

a = array.array('i', [1, 2, 3])
print(a)

'i' stands for integer array.


🔸 When to Use Arrays?

Use arrays for performance and memory efficiency when dealing with large numeric datasets.


🔸 Common Array Types
Type Code C Type Python Type
'i' int int
'f' float float
'u' Py_UNICODE Unicode

🔹 Key Difference: List vs Array

Feature List Array (array module)
Data Type Mixed Same type only
Built-in Yes Need to import module
Use Case General-purpose Numeric processing
Performance Slower Faster for numbers

Practice Questions

Q1. Write a Python program to create a list of your favorite fruits and print it.

Q2. Write a Python program to replace the 2nd element in a list with a new value.

Q3. Write a Python program to append a new number to a list.

Q4. Write a Python program to use pop() to remove the last element from a list.

Q5. Write a Python program to check if a value exists in a list using the in keyword.

Q6. Write a Python program to create an integer array using array.array.

Q7. Write a Python program to use a loop to print all values in an array.

Q8. Write a Python program to insert a value at index 1 in a list.

Q9. Write a Python program to use remove() to delete a value from a list.

Q10. Write a Python program to count how many times an element appears in a list using count().


Go Back Top