What is List in Python with examples

A list in Python is a collection of values (also known as elements) that are ordered and changeable.

Here are some examples: To Define a List, Accessing Elements of a list, Loop thru a list

# Defining a list
fruits = ["apple", "banana", "cherry"]

# Accessing elements
print(fruits[0]) # Output: apple

# Modifying elements
fruits[0] = "mango"
print(fruits) # Output: ['mango', 'banana', 'cherry']

# Loop through a list
for fruit in fruits:

# Check if item exists in list
if "banana" in fruits:
    print("Yes, 'banana' is in the list")

# List length
print(len(fruits)) # Output: 3

# Add elements to a list
print(fruits) # Output: ['mango', 'banana', 'cherry', 'orange']

# Remove elements from a list
print(fruits) # Output: ['mango', 'cherry', 'orange']

# Sort a list
print(fruits) # Output: ['cherry', 'mango', 'orange']

Lists in Python have several built-in methods that can be used to manipulate the data stored in the list.

Here are some of the most commonly used list methods along with examples:

  1. append(item): Adds an item to the end of the list.
fruits = ['apple', 'banana', 'cherry']
print(fruits) # Output: ['apple', 'banana', 'cherry', 'mango']
  1. insert(index, item): Inserts an item at a specific index.
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'mango')
print(fruits) # Output: ['apple', 'mango', 'banana', 'cherry']
  1. extend(list): Adds the elements of another list to the end of the original list.
fruits = ['apple', 'banana', 'cherry']
new_fruits = ['mango', 'grapes']
print(fruits) # Output: ['apple', 'banana', 'cherry', 'mango', 'grapes']
  1. remove(item): Removes the first occurrence of an item from the list.
fruits = ['apple', 'banana', 'cherry']
print(fruits) # Output: ['apple', 'cherry']
  1. pop(index): Removes the item at a specific index and returns its value. If no index is specified, it removes the last item.
fruits = ['apple', 'banana', 'cherry']
print(fruits) # Output: ['apple', 'cherry']
  1. index(item): Returns the index of the first occurrence of an item in the list.
fruits = ['apple', 'banana', 'cherry']
print(fruits.index('banana')) # Output: 1
  1. count(item): Returns the number of occurrences of an item in the list.
fruits = ['apple', 'banana', 'cherry', 'banana']
print(fruits.count('banana')) # Output: 2
  1. sort(): Sorts the items in the list in ascending order.
fruits = ['apple', 'banana', 'cherry']
print(fruits) # Output: ['apple', 'banana', 'cherry']
  1. reverse(): Reverses the order of the items in the list.
fruits = ['apple', 'banana', 'cherry']
print(fruits) # Output: ['cherry', 'banana', 'apple']

Previous Chapter – Taking User Inputs Next Chapter – Tuple

Leave a Comment