LIST

A list is a versatile and mutable data structure that allows you to store a collection of items. Lists are defined by enclosing the elements in square brackets [ ] and separating them with commas. Lists can contain elements of different data types, and you can change, add, or remove elements after the list is created.

my_list = [1, 2, 3, 'hello', True]

Creating a List

# Empty list

empty_list = []

 

# List with elements

fruits = ['apple', 'banana', 'orange']

 

# Mixed data types in a list

mixed_list = [1, 'hello', 3.14, True]

Accessing Elements:

You can access individual elements in a list using indexing. Python uses zero-based indexing, so the first element is at index 0.

fruits = ['apple', 'banana', 'orange']

first_fruit = fruits[0]

second_fruit = fruits[1]

 

print("First Fruit:", first_fruit)

print("Second Fruit:", second_fruit)

Slicing Lists:

You can also create sublists using slicing.

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

subset = numbers[1:4]  # Elements at index 1, 2, 3

print("Subset:", subset)

Modifying Lists:

fruits = ['apple', 'banana', 'orange']

 

# Changing an element

fruits[1] = 'grape'

 

# Adding elements

fruits.append('kiwi')  # Adds 'kiwi' to the end of the list

fruits.insert(1, 'pear')  # Inserts 'pear' at index 1

 

# Removing elements

removed_fruit = fruits.pop(2)  # Removes and returns the element at index 2

fruits.remove('apple')  # Removes the first occurrence of 'apple'

 

print("Modified Fruits:", fruits)

print("Removed Fruit:", removed_fruit)

List Operations

# Concatenation

list1 = [1, 2, 3]

list2 = ['a', 'b', 'c']

combined_list = list1 + list2

 

# Repetition

repeated_list = list1 * 3

 

print("Concatenated List:", combined_list)

print("Repeated List:", repeated_list)

Common List Methods

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

 

# Sorting

numbers.sort()

 

# Reversing

numbers.reverse()

 

# Length of the list

length = len(numbers)

 

# Finding index of an element

index_of_5 = numbers.index(5)

 

print("Sorted Numbers:", numbers)

print("Length of the List:", length)

print("Index of 5:", index_of_5)