Python Lists

A list is one of the most commonly used data structures in Python. It allows to store multiple items in a single variable & is highly flexible because lists can contain different data types including numbers, strings & even other lists.

Creating a List

The Lists are created using square brackets [].

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

Output:

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

List Characteristics

Ordered :

Items maintain their insertion order.
colors = ["Red", "Green", "Blue"]
print(colors[0])

Output:

Red

Mutable :

You can modify items after creation.

colors[1] = "Yellow"
print(colors)

Output:

['Red', 'Yellow', 'Blue']

List Slicing

The Slicing extracts a portion of a list.

numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])

Output:

[2, 3, 4]

Reverse a List

print(numbers[::-1])

Output:

[5, 4, 3, 2, 1]

Modifying List Elements

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

Output:

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

Adding Elements to a List

append()

Adds an item at the end.

fruits = ["Apple", "Mango"]
fruits.append("Orange")
print(fruits)

Output:

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

extend()

Adds multiple elements.

fruits.extend(["Grapes", "Pineapple"])
print(fruits)

List Length

Use len() to count elements.

numbers = [1, 2, 3, 4, 5]
print(len(numbers))

Output:

5

Looping Through a List

Using for Loop

fruits = ["Apple", "Mango", "Orange"]
for fruit in fruits:
print(fruit)

Using while Loop

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

List Methods

Method

Description

append()

Adds an item

insert()

Inserts at specific position

extend()

Adds multiple items

remove()

Removes specified item

pop()

Removes item by index

clear()

Removes all items

index()

Returns index of value

count()

Counts occurrences

sort()

Sorts the list

reverse()

Reverses the list

copy()

Creates a copy


Interview Questions

1)What is a Python List?

A list is an ordered mutable collection that can store multiple values &  allows duplicate elements.

2)Difference Between List and Tuple?

List

Tuple

Mutable

Immutable

Uses []

Uses ()

Slower

Faster

More memory

Less memory

3) How Do You Remove Duplicates?

numbers = [1, 2, 2, 3, 4, 4]
unique = list(set(numbers))
print(unique)

Conclusion

The Python lists are one of the most powerful & flexible data structures in the language. They allow developers to store, access, modify & process collections of data efficiently. Mastering list operations such as indexing, slicing, sorting, looping and list comprehensions is essential for becoming proficient in Python programming.