Lists in Python

Loading

A list is a built-in data structure in Python used to store multiple values in a single variable. Lists are ordered, mutable (modifiable), and allow duplicate values. They can hold different data types, such as integers, strings, and even other lists.


1. Creating a List

Lists are defined using square brackets [ ], with elements separated by commas.

Example: Creating Lists

# Empty list
empty_list = []

# List of integers
numbers = [1, 2, 3, 4, 5]

# List of strings
fruits = ["apple", "banana", "cherry"]

# Mixed data types
mixed = [1, "hello", 3.14, True]

# Nested list (list inside another list)
nested_list = [[1, 2], [3, 4]]

2. Accessing List Elements

You can access elements using indexing and slicing.

(a) Indexing (Zero-based Indexing)

fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # First element
print(fruits[1]) # Second element
print(fruits[-1]) # Last element

Output:

apple
banana
cherry

(b) Slicing (Extracting a Subset)

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # Elements from index 1 to 3
print(numbers[:3]) # First 3 elements
print(numbers[2:]) # Elements from index 2 to end
print(numbers[-3:]) # Last 3 elements

Output:

[20, 30, 40]
[10, 20, 30]
[30, 40, 50]
[30, 40, 50]

3. Modifying a List

Lists are mutable, meaning their elements can be changed.

(a) Changing Elements

numbers = [10, 20, 30, 40]
numbers[1] = 25 # Change second element
print(numbers)

Output:

[10, 25, 30, 40]

(b) Adding Elements

numbers.append(50)  # Add to end
numbers.insert(2, 15) # Insert at index 2
print(numbers)

Output:

[10, 25, 15, 30, 40, 50]

(c) Removing Elements

numbers.remove(30)  # Remove first occurrence of 30
print(numbers)

del numbers[1] # Delete element at index 1
print(numbers)

popped = numbers.pop() # Remove last element
print(popped)
print(numbers)

Output:

[10, 25, 15, 40, 50]
[10, 15, 40, 50]
50
[10, 15, 40]

4. Looping Through a List

You can use loops to iterate over lists.

(a) Using for Loop

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

(b) Using while Loop

i = 0
while i < len(fruits):
print(fruits[i])
i += 1

Output:

apple
banana
cherry

(c) Using enumerate() (Index + Value)

for index, fruit in enumerate(fruits):
print(index, fruit)

Output:

0 apple
1 banana
2 cherry

5. List Comprehensions

A list comprehension is a concise way to create lists.

Example: Creating a List with for Loop

squares = [x**2 for x in range(1, 6)]
print(squares)

Output:

[1, 4, 9, 16, 25]

Example: Filtering a List

evens = [x for x in range(10) if x % 2 == 0]
print(evens)

Output:

[0, 2, 4, 6, 8]

6. Common List Methods

MethodDescription
append(x)Adds x to the end of the list
insert(i, x)Inserts x at index i
remove(x)Removes the first occurrence of x
pop([i])Removes and returns item at index i (last item if i is omitted)
index(x)Returns the index of the first occurrence of x
count(x)Returns the count of x in the list
sort()Sorts the list in ascending order
reverse()Reverses the list
copy()Returns a shallow copy of the list

Example: Using List Methods

numbers = [3, 1, 4, 1, 5, 9]

numbers.sort() # Sort in ascending order
print(numbers)

numbers.reverse() # Reverse order
print(numbers)

print(numbers.count(1)) # Count occurrences of 1

Output:

[1, 1, 3, 4, 5, 9]
[9, 5, 4, 3, 1, 1]
2

7. Copying a List

(a) Using copy()

original = [1, 2, 3]
copy_list = original.copy()
copy_list.append(4)
print(original)
print(copy_list)

Output:

[1, 2, 3]
[1, 2, 3, 4]

(b) Using Slicing ([:])

copy_list = original[:]

(c) Using list()

copy_list = list(original)

8. Joining Lists

Example: Concatenation (+)

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)

Output:

[1, 2, 3, 4, 5, 6]

Example: Extending a List (extend())

a.extend(b)
print(a)

Output:

[1, 2, 3, 4, 5, 6]

9. Checking if an Item Exists

fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Banana is in the list!")

Output:

Banana is in the list!

10. Clearing a List

numbers = [1, 2, 3]
numbers.clear()
print(numbers)

Output:

[]

Leave a Reply

Your email address will not be published. Required fields are marked *