MyInternships.in

Python Data Structures

Python Lists

A list is an ordered, changeable collection that can hold values of any data type. Lists are one of the most-used data structures in Python.


Creating a List

You create a list by placing comma-separated values inside square brackets and assigning it to a variable. A list can mix data types, though most real-world lists hold items of one kind.

Creating lists
Python
fruits = ["apple", "banana", "mango"]
mixed = [1, "two", 3.0, True]
empty = []

print(fruits)
print(len(fruits))

Indexing and Accessing Items

Each item in a list has a position called an index, starting at 0 for the first item. Negative indices count backward from the end, so -1 is always the last item — very handy in loops and functions.

Accessing by index
Python
fruits = ["apple", "banana", "mango"]

print(fruits[0])   # apple
print(fruits[-1])  # mango
print(fruits[1:])  # ['banana', 'mango']

Lists Are Mutable

Unlike strings and tuples, lists are mutable — you can change, add, or remove elements after creation without making a new list. This makes them ideal for data that grows or shrinks while your program runs.

Modifying, adding and removing
Python
fruits = ["apple", "banana", "mango"]

fruits[1] = "grape"     # change an item
fruits.append("kiwi")   # add to the end
fruits.remove("apple")  # remove by value
del fruits[0]           # remove by index

print(fruits)

Nesting Lists

A list can contain other lists, which is useful for grids, matrices, or grouped records. You access an inner item by chaining indices.

A nested list (2D grid)
Python
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][0])  # 3

When to Use a List

  • Storing an ordered collection you plan to loop over, like student names or scores.
  • Data that will grow or shrink, such as a shopping cart or task queue.
  • Any time order and duplicates matter — use a set instead if you need only unique values.
💡

Use type(x) or the list() function to check or convert other iterables like strings and tuples into a list.

Frequently Asked Questions

What is the difference between a list and an array in Python?+

A Python list can hold mixed data types and resizes automatically, while the built-in array module (and NumPy arrays) store one fixed data type and are more memory-efficient for large numeric datasets.

Are Python lists ordered?+

Yes. Lists keep items in the exact order you insert them, and that order is preserved until you explicitly sort or shuffle the list.

How do I copy a list without affecting the original?+

Use fruits.copy() or fruits[:] to make a shallow copy. Assigning list_b = list_a just creates a second reference to the same list, so changes to one affect the other.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships