MWZ

MINDWAREZONE

Lists

What is a List?

  • A List is an ordered collection used to store multiple values.
  • It allows you to keep several items inside a single variable.
  • Items in a list are separated by commas and written inside square brackets [].
  • Items are separated by commas ,.
  • Lists are mutable, which means their elements can be added, removed, or modified after the list is created.

Example:

fruits = ["Apple", "Banana", "Mango"] 
print(fruits)
            

Output

['Apple', 'Banana', 'Mango']
            

Why Use Lists?

Lists make it easier to manage and organize multiple values.

Benefits of Using Lists

  • Store multiple values in a single variable.
  • Access items easily using their position (index).
  • Add new items whenever needed.
  • Remove existing items.
  • Modify items after creation.
  • Loop through all items efficiently.

Example

Without a list:

fruit1 = "Apple" 
fruit2 = "Banana" 
fruit3 = "Mango"
            

Using a list:

fruits = ["Apple", "Banana", "Mango"]
            

The second approach is shorter, cleaner, and easier to manage.

Features of Lists

Python lists have several useful features.

1. Ordered

List items maintain their order.

fruits = ["Apple", "Banana", "Mango"] 
print(fruits)
            

Output

['Apple', 'Banana', 'Mango']
            

The items appear in the same order in which they were added.

2. Mutable (Changeable)

Lists can be modified after creation.

fruits = ["Apple", "Banana", "Mango"] 
fruits[1] = "Orange" 
print(fruits)
            

Output

['Apple', 'Orange', 'Mango']
            

3. Allow Duplicate Values

Lists can contain duplicate items.

fruits = ["Apple", "Banana", "Apple"] 
print(fruits)
            

Output

['Apple', 'Banana', 'Apple']
            

4. Can Store Different Data Types

A single list can contain multiple data types.

data = ["John", 25, 5.8, True] 
print(data)
            

Creating a List

Lists are created using square brackets [].

Syntax

list_name = [item1, item2, item3]
            

Example 1

colors = ["Red", "Blue", "Green"] 
print(colors)
            

Example 2

numbers = [10, 20, 30, 40] 
print(numbers)
            

Example 3

cities = ["Delhi", "Mumbai", "Chennai"] 
print(cities)
            

Empty Lists

An empty list is a list that contains no items.

Creating an Empty List

my_list = [] 
print(my_list)
            

Output

[]
            

Why Use Empty Lists?

Empty lists are useful when you want to add items later.

fruits = [] 
fruits.append("Apple") 
fruits.append("Banana") 
print(fruits)
            

Output

['Apple', 'Banana']
            

Lists with Different Data Types

Python lists can store different types of data in the same list.

Example 1

data = ["John", 25, 5.8, True] 
print(data)
            

Example 2

mixed_list = ["Python", 100, 9.99, False] 
print(mixed_list)
            

Example 3

student = ["Rahul", 18, 85.5] 
print(student)