List in Python
List in Python
List Methods:
Definition: List methods are built-in functions in Python that can be used to
perform specific actions on lists.
These methods allow you to add, remove, find, sort, and modify list items
directly.
Most list methods change the original list (because lists are mutable), and they
are used by writing:
list_name.method_name(arguments)
Common List Methods with Examples
1. append() – Adds an item to the end of the list
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']
2. insert() – Inserts an item at a specific index
fruits.insert(1, "orange")
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']
3. remove() – Removes the first occurrence of an item
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'cherry']
4. pop() – Removes and returns the item at the given index (or last item by
default)
fruits.pop()
print(fruits) # Output: ['apple', 'orange']
5. index() – Returns the index of the first matching item
numbers = [10, 20, 30, 20]
print(numbers.index(20)) # Output: 1
6. count() – Returns how many times an item appears
print(numbers.count(20)) # Output: 2
7. sort() – Sorts the list in ascending order
numbers.sort()
print(numbers) # Output: [10, 20, 20, 30]
8. reverse() – Reverses the list order
numbers.reverse()
print(numbers) # Output: [30, 20, 20, 10]
9. clear() – Removes all items from the list
numbers.clear()
print(numbers) # Output: []
10. copy()
Creates a shallow copy of the list (a new list with the same elements).
original = [1, 2, 3]
copied = original.copy()
copied.append(4)
print(original) # Output: [1, 2, 3]
print(copied) # Output: [1, 2, 3, 4]
11. extend()
Adds all items from another list (or iterable) to the end of the list.
list1 = [1, 2, 3]
list2 = [4, 5]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5]
3. sort(reverse=True)
sort() is an option that sorts the list in descending (from largest to smallest)
order.
numbers = [5, 3, 8, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 3, 1]
The list() Function:
Definition: The list() function is a built-in Python function that is used to create
a new list.
You can use it to:
Convert other iterable data types (like tuples, strings, sets, or dictionaries)
into lists.
Create an empty list if no argument is provided.
The function takes an iterable as an argument and returns a new list containing
all the elements of that iterable.
Syntax:
list(iterable)
iterable (optional): Any iterable object like tuple, string, set, etc.
If you don’t pass any argument, it returns an empty list [].
Examples of list() function
1. Creating an empty list
empty_list = list()
print(empty_list) # Output: []
2. Converting a tuple into a list
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3]
3. Converting a string into a list of characters
my_string = "hello"
char_list = list(my_string)
print(char_list) # Output: ['h', 'e', 'l', 'l', 'o']
4. Converting a set into a list
my_set = {10, 20, 30}
list_from_set = list(my_set)
print(list_from_set) # Output: [10, 20, 30] (order may vary because sets are
unordered)
5. Using list() with a dictionary
my_dict = {'a': 1, 'b': 2}
list_from_dict = list(my_dict)
print(list_from_dict) # Output: ['a', 'b'] (only keys are converted)
List Comprehension:
Definition: List comprehension is a concise and powerful way to create new
lists by applying an expression to each item in an existing iterable (like a list,
tuple, or range), optionally filtering items with a condition — all in a single line
of code!
It helps make your code shorter, cleaner, and often faster compared to using
traditional loops to build lists.
Syntax:
new_list = [expression for item in iterable if condition]
expression: The operation or value to add to the new list.
item: Variable representing each element in the iterable.
iterable: Any sequence or collection you want to loop through.
condition (optional): A filter that decides which items to include.
Examples of List Comprehension
1. Create a list of squares
squares = []
for x in range(5):
squares.append(x**2)
print(squares) # Output: [0, 1, 4, 9, 16]
Using list comprehension:
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
2. List of even numbers only
evens = []
for x in range(10):
if x % 2 == 0:
evens.append(x)
print(evens) # Output: [0, 2, 4, 6, 8]
Using list comprehension with condition:
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
3. Convert all strings to uppercase
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names) # Output: ['ALICE', 'BOB', 'CHARLIE']
4. Create list from another list with condition
Get numbers greater than 5 from a list:
nums = [2, 5, 8, 1, 9, 3]
filtered = [num for num in nums if num > 5]
print(filtered) # Output: [8, 9]
5. Nested list comprehension
Flatten a matrix (list of lists) into a single list:
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat) # Output: [1, 2, 3, 4, 5, 6]
6. Using For Loop
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares) # Output: [1, 4, 9, 16, 25]
Using List Comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
7. For Loop with Condition vs List Comprehension with Condition
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) # Output: [2, 4, 6]
List comprehension:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
8. For Loop (simple)
numbers = []
for i in range(5):
numbers.append(i)
print(numbers) # Output: [0, 1, 2, 3, 4]
List Comprehension (simple)
numbers = [i for i in range(5)]
print(numbers) # Output: [0, 1, 2, 3, 4]
9. Using For Loop with vowels
text = "hello"
vowels = []
for char in text:
if char in "aeiou":
vowels.append(char)
print(vowels) # Output: ['e', 'o']
Using List Comprehension
text = "hello"
vowels = [char for char in text if char in "aeiou"]
print(vowels) # Output: ['e', 'o']
10. Using For Loop with list
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
fruits_with_a = []
for fruit in fruits:
if 'a' in fruit:
fruits_with_a.append(fruit)
print(fruits_with_a)
# Output: ['apple', 'banana', 'date', 'grape']
Using List Comprehension:
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
fruits_with_a = [fruit for fruit in fruits if 'a' in fruit]
print(fruits_with_a)
# Output: ['apple', 'banana', 'date', 'grape']
Example: Extract vowels from each fruit name into a nested list
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
vowels = "aeiou"
vowels_in_fruits = [[char for char in fruit if char in vowels] for fruit in fruits]
print(vowels_in_fruits)
Output:
[['a', 'e'], ['a', 'a', 'a'], ['e'], ['a', 'e'], ['i'], ['a', 'e']]
Fruits list example:
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
1. Reverse the list using reverse() method (in-place):
fruits.reverse()
print(fruits)
Output:
['grape', 'fig', 'date', 'cherry', 'banana', 'apple']
2. Reverse the list using slicing (creates a new reversed list):
reversed_fruits = fruits[::-1]
print(reversed_fruits)
Output:
['grape', 'fig', 'date', 'cherry', 'banana', 'apple']
3. Reverse the list using reversed() function (returns iterator):
reversed_fruits = list(reversed(fruits))
print(reversed_fruits)
Output:
['grape', 'fig', 'date', 'cherry', 'banana', 'apple']
Original list:
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
4. Code to reverse list order and reverse each fruit’s letters:
# Reverse the list order and reverse letters of each fruit
reversed_fruits = [fruit[::-1] for fruit in fruits[::-1]]
print(reversed_fruits)
Output:
['eparg', 'gif', 'etad', 'yrrehc', 'ananab', 'elppa']
5. Example
fruits = ["apple", "banana", "cherry"]
reversed_fruits = [fruit[::-1] for fruit in fruits]
print(reversed_fruits)
['elppa', 'ananab', 'yrrehc']
List user through create
1. Integer List
int_list = []
n = int(input("How many integers do you want to add? "))
for i in range(n):
num = int(input("Enter an integer: "))
int_list.append(num)