PYTHON Tutorial



LIST IN PYTHON


📋 Lists in Python

A list in Python is an ordered collection of elements. Lists can store items of any data type and are mutable, meaning their values can be changed after the list is created. They are defined by placing items inside square brackets, separated by commas.

🔸 Creating a List

Lists are created by enclosing elements in square brackets.

# List Example
fruits = ["apple", "banana", "cherry"]
print(fruits)
# Output: ['apple', 'banana', 'cherry']
  

🔸 Accessing List Elements

You can access list elements by their index (starting from 0).

# Accessing Elements
fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Access first element
print(fruits[1])  # Access second element
# Output:
# apple
# banana
  

🔸 Modifying List Elements

Lists are mutable, which means you can modify the values of the elements.

# Modifying Elements
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"  # Change second element
print(fruits)
# Output: ['apple', 'blueberry', 'cherry']
  

🔸 Adding Elements to a List

You can add items to a list using methods like append(), insert(), and extend().

# Adding Elements
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")  # Adds to the end
fruits.insert(1, "kiwi")  # Inserts at specified index
print(fruits)
# Output: ['apple', 'kiwi', 'banana', 'cherry', 'orange']
  

🔸 Removing Elements from a List

You can remove items from a list using methods like remove(), pop(), or del.

# Removing Elements
fruits = ["apple", "banana", "cherry", "orange"]
fruits.remove("banana")  # Removes by value
fruits.pop(1)  # Removes by index
del fruits[0]  # Removes by index
print(fruits)
# Output: ['cherry']
  

🔸 List Slicing

You can extract a portion of a list using slicing. The syntax is list[start:end], where the start index is inclusive and the end index is exclusive.

# List Slicing
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[1:3])  # From index 1 to 2 (3 is excluded)
# Output: ['banana', 'cherry']
  

🔸 List Length

You can get the length of a list using the len() function.

# List Length
fruits = ["apple", "banana", "cherry"]
print(len(fruits))
# Output: 3
  

🔸 Nested Lists

Lists can contain other lists as elements, creating a nested structure.

# Nested Lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1])  # Access the second row
# Output: [4, 5, 6]
  
💡 Tip: - Lists are versatile and can store different data types like strings, numbers, or even other lists. - Lists in Python are zero-indexed, meaning the first item in the list is at index 0.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review