In Python, a list is a collection of items that are ordered, changeable (mutable), and allow duplicate values.They can hold elements of different data types, such as integers, strings, floats, or even other lists. Lists are created using square [ ] brackets.
thislist = ["apple", "banana", "cherry"]
print(thislist)
In Python lists are defined as objects with the data type class 'list'
my_list = [10, 20, 30]
print(type(my_list))
In Python, lists are ordered collections, which means the items have a defined order, and that order will not change unless explicitly modified.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Accesses the first item
In Python, lists can contain duplicate values. This means the same element can appear multiple times in a list without any restrictions.
numbers = [10, 20, 10, 30, 20]
print(numbers)
In Python, lists can store items of any data type, and even a mix of multiple data types in a single list.
mixed_list = [10, "Hello", 3.14, True]
print(mixed_list)
In Python, you can use the len() function to find out how many elements are present in a list.
my_list = [10, 20, 30, 40, 50]
print(len(my_list))
The list() constructor is a built-in function used to create a list from an iterable that can be looped over like a string, tuple, set, or even another list. It's especially useful when you need to convert or copy data into a list format.
1. Creating list From a String
result = list('Python')
print(result)
2.Creating list from a Tuple
result = list((1, 2, 3))
print(result)
3. Creating list from a Set
result = list({"apple", "banana", "cherry", "apple"})
print(result)
4. Creating list from a Dictionary
result = list({'Name': 'Raj', 'age': 25})
print(result)
5. Creating list from a Range
result = list(range(1,11))
print(result)
In Python, lists are mutable, which means you can change, add, or remove items after the list has been created.
my_list = ["apple", "banana", "cherry"]
my_list[1] = "orange"
print(my_list)
In Python, lists are mutable, which means you can change, update, add, or delete elements after the list has been created
fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'mango'
print(fruits)
In Python, you can access items in a list using index numbers. You can use positive or negative indexing.
colors = ["red", "green", "blue", "yellow", "purple"]
print(colors[1])
print(colors[-2])
print(colors[0])
print(colors[-1])
print(colors[-0])
print(colors[5]) # ❌ IndexError: list index out of range
| Argument | Description | Default Value |
|---|---|---|
| start | The index where the slice starts (inclusive). | 0 (if step is positive), -1 (if step is negative) |
| end | The index where the slice ends (exclusive). | len(S) (if step is positive), -len(S) (if step is negative) |
| step | The interval between indices in the slice. | 1 (default) |
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_list[:])
print(my_list[2:])
print(my_list[:4])
print(my_list[1:4])
print(my_list[::2])
print(my_list[1:5:2])
print(my_list[2::2])
print(my_list[:4:2])
print(my_list[4:1:-1])
print(my_list[5:1:-2])
print(my_list[0:10:-2])
print(my_list[5::-2])
print(my_list[:5:-2])
print(my_list[::-1])
List traversing refers to iterating over all the elements of a list to perform operations or access each element. In Python, this can be done using various methods like for loops, while loops, and list comprehensions.
# Using a simple for loop
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
# Using a simple while loop
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result)
Repeating a list means making multiple copies of the elements inside the list and combining them into a new list.
list1 = [1, 2, 3]
result = list1 * 3
print(result)
Comparing lists means checking if two lists are equal or if one list is greater or smaller based on their elements.
# Equality
print([1, 2, 3] == [1, 2, 3])
# Not Equal
print([1, 2, 3] != [3, 2, 1])
# Less than (element-wise comparison)
print([1, 2, 30] < [1, 20, 4])
# Greater than
print([7, 3, 5] > [1, 20, 90])
# Shorter list vs longer
print([1, 2] < [1, 2, 0])
# Comparing strings in list
print(['apple'] < ['banana'])
In Python, variables refer to objects in memory. The is operator checks if two variables point to the same object, while == checks if their values are the same.
# Value Comparison
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2)
# Identity Comparison
list3 = list1
print(list1 is list2)
print(list1 is list3)
Aliasing in Python occurs when two or more variables refer to the same object in memory. Changes made through one variable affect all other variables referring to the same object.
# Aliasing Example
a = [1, 2, 3]
b = a # b is now aliasing a
# Modify b
b.append(4)
print("a:", a) # [1, 2, 3, 4]
print("b:", b) # [1, 2, 3, 4]
Python provides various functions and methods that allow you to manipulate lists efficiently.
| Function/Method | Description | Example |
|---|---|---|
| len() | Returns the number of elements | `len([1, 2, 3]) → 3` |
| max() | Returns the largest element | `max([1, 2, 3]) → 3` |
| min() | Returns the smallest element | `min([1, 2, 3]) → 1` |
| sum() | Returns the sum of elements | `sum([1, 2, 3]) → 6` |
| append() | Adds an element at the end of the list | `[1, 2].append(3)` → `[1, 2, 3]` |
| clear() | Removes all the elements from the list | `[1, 2, 3].clear()` → `[]` |
| copy() | Returns a copy of the list | `[1, 2].copy()` → `[1, 2]` |
| count() | Returns the number of elements with the specified value | `[1, 2, 2, 3].count(2)` → `2` |
| extend() | Adds the elements of a list (or any iterable), to the end of the current list | `[1, 2].extend([3, 4])` → `[1, 2, 3, 4]` |
| index() | Returns the index of the first element with the specified value | `[1, 2, 3].index(2)` → `1` |
| insert() | Adds an element at the specified position | `[1, 2].insert(1, 1.5)` → `[1, 1.5, 2]` |
| pop() | Removes the element at the specified position | `[1, 2, 3].pop(1)` → `2` |
| remove() | Removes the item with the specified value | `[1, 2, 3].remove(2)` → `[1, 3]` |
| reverse() | Reverses the order of the list | `[1, 2, 3].reverse()` → `[3, 2, 1]` |
| sort() | Sorts the list | `[3, 1, 2].sort()` → `[1, 2, 3]` |
The len() function returns the number of elements in the list.
my_list = [1, 2, 3]
print(len(my_list))
The max() function returns the largest item in an iterable (e.g., list, tuple) or the largest of two or more arguments.
numbers = [1, 5, 3, 9, 2]
print(max(numbers))
The min() function returns the smallest item in an iterable (e.g., list, tuple) or the smallest of two or more arguments.
numbers = [1, 5, 3, 9, 2]
print(min(numbers))
The sum() function returns the sum of all items in an iterable (e.g., list, tuple) or the sum of two or more arguments.
numbers = [1, 2, 3, 4, 5]
print(sum(numbers))
The append() method appends an element to the end of the list.
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
The clear() method removes all the elements from a list.
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
The copy() method returns a copy of the specified list.
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
The count() method returns the number of elements with the specified value.
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
The extend() method adds the specified list elements (or any iterable) to the end of the current list.
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
The index() method returns the position at the first occurrence of the specified value.
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
The insert() method inserts the specified value at the specified position.
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
The pop() method removes and returns the element at the specified index position.
fruits = ['apple', 'banana', 'cherry']
x = fruits.pop(1)
The remove() method removes the first occurrence of the element with the specified value.
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
The reverse() method reverses the sorting order of the elements.
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s).
reverse Optional. reverse=True will sort the list descending. Default is reverse=False
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
The del statement is used to remove an element at a specific index or delete the entire list.
fruits = ["apple", "banana", "cherry", "orange"]
del fruits[1] # Delete a specific item
print(fruits)
# Delete a range of items
del fruits[1:3]
# Delete entire list
del fruits
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
newlist = [expression for item in iterable if condition == True]
# List comprehension to remove "apple" from the list
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
# Simple list comprehension to copy all items from the original list
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits]
# List comprehension to generate a list of numbers from 0 to 9
newlist = [x for x in range(10)]
# List comprehension to generate numbers less than 5 from a range of 0 to 9
newlist = [x for x in range(10) if x < 5]
# List comprehension to convert all elements to uppercase
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x.upper() for x in fruits]
# List comprehension to create a list of "hello" for each item in the original list
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = ['hello' for x in fruits]
# List comprehension to replace "banana" with "orange", while keeping other items unchanged
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]