Python List methods
Python list methods are built-in functions that allow us to perform various operations on lists, such as
adding, removing, or modifying elements. In this article, we’ll explore all Python list methods with
a simple example.
List Methods
Let's look at different list methods in Python:
append(): Adds an element to the end of the list.
copy(): Returns a shallow copy of the list.
clear(): Removes all elements from the list.
count(): Returns the number of times a specified element appears in the list.
extend(): Adds elements from another list to the end of the current list.
index(): Returns the index of the first occurrence of a specified element.
insert(): Inserts an element at a specified position.
pop(): Removes and returns the element at the specified position (or the last element if no
index is specified).
remove(): Removes the first occurrence of a specified element.
reverse(): Reverses the order of the elements in the list.
sort(): Sorts the list in ascending order (by default).
Examples of List Methods
append():
Syntax: list_name.append(element)
In the code below, we will add an element to the list.
a = [1, 2, 3]
# Add 4 to the end of the list
a.append(4)
print(a) Output
[1, 2, 3, 4]
copy():
Syntax: list_name.copy()
In the code below, we will create a copy of a list.
a = [1, 2, 3]
# Create a copy of the list
b = a.copy()
print(b)
Output
[1, 2, 3]
clear():
Syntax: list_name.clear()
In the code below, we will clear all elements from the list.
a = [1, 2, 3]
# Remove all elements from the list
a.clear()
print(a)
Output
[]
count():
Syntax: list_name.count(element)
In the code below, we will count the occurrences of a specific element in the list.
a = [1, 2, 3, 2]
# Count occurrences of 2 in the list
print(a.count(2))
Output
2
extend():
Syntax: list_name.extend(iterable)
In the code below, we will extend the list by adding elements from another list.
a = [1, 2]
# Extend list a by adding elements from list [3, 4]
a.extend([3, 4])
print(a)
Output
[1, 2, 3, 4]
index():
Syntax: list_name.index(element)
In the code below, we will find the index of a specific element in the list.
a = [1, 2, 3]
# Find the index of 2 in the list
print(a.index(2))
Output
1
insert():
Syntax: list_name.insert(index, element)
In the code below, we will insert an element at a specific position in the list.
a = [1, 3]
# Insert 2 at index 1
a.insert(1, 2)
print(a)
Output
[1, 2, 3]
pop():
Syntax: list_name.pop(index)
In the code below, we will remove the last element from the list.
a = [1, 2, 3]
# Remove and return the last element in the list
a.pop()
print(a)
Output
[1, 2]
remove():
Syntax: list_name.remove(element)
In the code below, we will remove the first occurrence of a specified element from the list.
a = [1, 2, 3]
# Remove the first occurrence of 2
a.remove(2)
print(a)
Output
[1, 3]
reverse():
Syntax: list_name.reverse()
In the code below, we will reverse the order of the elements in the list.
a = [1, 2, 3]
# Reverse the list order
a.reverse()
print(a)
Output
[3, 2, 1]
sort():
Syntax: list_name.sort(key=None, reverse=False)
In the code below, we will sort the elements of the list in ascending order
a = [3, 1, 2]
# Sort the list in ascending order
a.sort()
print(a)
Output:
[1, 2, 3]
Built-in functions in List:
Python provides several built-in functions that are commonly used with lists to perform
various operations. These functions are readily available without requiring any imports.
Common Built-in Functions for Lists:
len(): Returns the number of items in a list.
Ex:
my_list = [10, 20, 30, 40]
length = len(my_list)
print(length) # Output: 4
max(): Returns the largest item in a list.
Ex:
numbers = [5, 1, 9, 2]
maximum = max(numbers)
print(maximum) # Output: 9
min(): Returns the smallest item in a list.
Ex:
numbers = [5, 1, 9, 2]
minimum = min(numbers)
print(minimum) # Output: 1
sum(): Returns the sum of all items in a list (requires numeric items).
Ex:
prices = [10.5, 20.0, 5.5]
total = sum(prices)
print(total) # Output: 36.0
sorted(): Returns a new sorted list from the items of an iterable (e.g., a list) in
ascending order by default. It does not modify the original list.
Ex:
unsorted_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(unsorted_list)
print(sorted_list) # Output: [1, 1, 3, 4, 5, 9]
print(unsorted_list) # Output: [3, 1, 4, 1, 5, 9] (original list unchanged)
list(): Creates a new list from an iterable. This is often used for type conversion.
Ex:
my_tuple = (1, 2, 3)
new_list = list(my_tuple)
print(new_list) # Output: [1, 2, 3]
any(): Returns True if at least one item in an iterable is true, False otherwise.
Ex:
bool_list = [False, True, False]
result = any(bool_list)
print(result) # Output: True
all(): Returns True if all items in an iterable are true, False otherwise.
Ex:
bool_list = [True, True, True]
result = all(bool_list)
print(result) # Output: True
Operations performed on List:
Traversing a list:
Traversing a list in Python refers to the process of accessing each element within the list,
typically to perform an operation on it. Several common methods exist for achieving this:
1. Using a for loop (Direct Iteration):
This is the most Pythonic and generally preferred method for simple traversal.
my_list = [10, 20, 30, 40, 50]
for item in my_list:
print(item)
2. Using a for loop with range() and len():
This method allows access to elements by their index, which is useful when you need to
know the position or modify elements in place.
my_list = [10, 20, 30, 40, 50]
for i in range(len(my_list)):
print(f"Element at index {i}: {my_list[i]}")
3. Using a while loop:
While less common for simple traversal than for loops, while loops can be used when you
need more control over the iteration condition.
my_list = [10, 20, 30, 40, 50]
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
Concatenation:
Concatenating lists in Python involves combining two or more lists into a single, larger
list. Several methods can achieve this:
Using the + operator: This is the most straightforward method for concatenating two
lists. It creates a new list containing all elements from the first list followed by all
elements from the second list.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list)
Using the extend() method: This method modifies an existing list by appending all
elements from another iterable (like another list) to its end.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
Repitition of List(Replicating list):
Python allows us to repeat or replicate the elements of the list using repetition operator which
is denoted by symbol ‘*’. We can also assign the repetition value of a list to another list.
Ex:
List1=[1,2,3]
List2=List1*3
Print(List2)
Output: [1,2,3,1,2,3,1,2,3]
Membership Operator:
In Python, membership operators are used to test for the presence of a value within a
sequence, such as a list. There are two primary membership operators:
in operator:
o This operator returns True if the specified value is found within the sequence,
and False otherwise.
o Example:
Python
my_list = [10, 20, 30, 40]
print(20 in my_list) # Output: True
print(50 in my_list) # Output: False
not in operator:
o This operator returns True if the specified value is not found within the
sequence, and False otherwise. It is essentially the logical negation of
the in operator.
o Example:
Python
my_list = [10, 20, 30, 40]
print(50 not in my_list) # Output: True
print(20 not in my_list) # Output: False
These operators are not limited to lists and can also be used with other sequence types in
Python, such as strings, tuples, and sets. They provide a concise and readable way to check
for element existence within collections.
Comparing the lists:
Comparing lists in Python can be performed in several ways, depending on whether the order
of elements matters and what kind of comparison is desired.
1. Exact Match (Content and Order)
To check if two lists are identical in both content and order, use the equality operator (==):
Python
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [3, 2, 1]
print(list1 == list2) # True
print(list1 == list3) # False
2. Match Content (Regardless of Order)
To check if two lists contain the same elements, irrespective of their order,
use collections.Counter or sort the lists:
a) Using collections.Counter:
Python
from collections import Counter
list1 = [1, 2, 3]
list2 = [3, 2, 1]
print(Counter(list1) == Counter(list2)) # True
b) Sorting and Comparing:
Python
list1 = [1, 2, 3]
list2 = [3, 2, 1]
print(sorted(list1) == sorted(list2)) # True
3. Finding Differences or Similarities
To find elements present in one list but not the other, or common elements, convert the lists
to set objects and use set operations:
Python
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
set1 = set(list1)
set2 = set(list2)
# Elements in list1 but not in list2
print(set1 - set2) # {1, 2}
# Elements in list2 but not in list1
print(set2 - set1) # {5, 6}
# Common elements
print(set1.intersection(set2)) # {3, 4}
4. Comparing Elements at Corresponding Indices
To check if elements at the same index in two lists are equal, especially for lists of potentially
different lengths, use zip and all():
Python
list1 = [1, 2, 3]
list2 = [1, 2, 4]
# Check if all corresponding elements are equal up to the length of the shorter list
print(all(a == b for a, b in zip(list1, list2))) # False
Slicing:
Python list slicing is fundamental concept that let us easily access specific elements in a list.
In this article, we’ll learn the syntax and how to use both positive and negative indexing for
slicing with examples.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements from index 1 to 4 (excluded)
print(a[1:4])
Output
[2, 3, 4]
Python List Slicing Syntax
Parameters:
start (optional): Index to begin the slice (inclusive). Defaults to 0 if omitted.
end (optional): Index to end the slice (exclusive). Defaults to the length of list if
omitted.
step (optional): Step size, specifying the interval between elements. Defaults to 1 if
omitted.
Ex:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get all elements in the list
print(a[::])
print(a[:])
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: Using [:] & [::] without specifying any start, end, or step returns all elements
of the list.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements starting from index 2
# to the end of the list
b = a[2:]
print(b)
# Get elements starting from index 0
# to index 3 (excluding 3th index)
c = a[:3]
print(c)
Output
[3, 4, 5, 6, 7, 8, 9]
[1, 2, 3]
Get all items between two positions
To extract elements between two specific positions, specify both the start and end indices
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements from index 1
# to index 4 (excluding index 4)
b = a[1:4]
print(b)
Output
[2, 3, 4]
Get items at specified intervals
To extract elements at specific intervals, use the step parameter.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get every second element from the list
# starting from the beginning
b = a[::2]
print(b)
# Get every third element from the list
# starting from index 1 to 8(exclusive)
c = a[1:8:3]
print(c)
Output
[1, 3, 5, 7, 9]
[2, 5, 8]
Negative Indexing
Negative indexing is useful for accessing elements from the end of the list. The last
element has an index of -1, the second last element -2, and so on.
Extract elements using negative indices
This example shows how to use negative numbers to access elements from the list starting
from the end. Negative indexing makes it easy to get items without needing to know the
exact length of the list.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements starting from index -2
# to end of list
b = a[-2:]
print(b)
# Get elements starting from index 0
# to index -3 (excluding 3th last index)
c = a[:-3]
print(c)
# Get elements from index -4
# to -1 (excluding index -1)
d = a[-4:-1]
print(d)
# Get every 2nd elements from index -8
# to -1 (excluding index -1)
e = a[-8:-1:2]
print(e)
Output
[8, 9]
[1, 2, 3, 4, 5, 6]
[6, 7, 8]
[2, 4, 6, 8]
Python Tuples ?
Are sequence that are used to store a tuple of values of any type
Tuples are immutable i.e. you cannot change the elements of tuple in place.
Python will create a fresh tuple when we make changes to an element of tuple.
A tuple in Python is an immutable ordered collection of elements.
Tuples are similar to lists, but unlike lists, they cannot be changed after their creation
(i.e., they are immutable).
Tuples can hold elements of different data types.
The main characteristics of tuples are being ordered , heterogeneous and immutable.
Creating a Tuple
A tuple is created by placing all the items inside parentheses (), separated by commas. A tuple
can have any number of items and they can be of different data types.
Example:
tup = ()
print(tup)
# Using String
tup = ('Geeks', 'For')
print(tup)
# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))
# Using Built-in Function
tup = tuple('Geeks')
print(tup)
Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Creating a Tuple with Mixed Datatypes.
Tuples can contain elements of various data types, including other
tuples, lists, dictionaries and even functions.
Example:
tup = (5, 'Welcome', 7, 'Geeks')
print(tup)
# Creating a Tuple with nested tuples
tup1 = (0, 1, 2, 3)
tup2 = ('python', 'geek')
tup3 = (tup1, tup2)
print(tup3)
# Creating a Tuple with repetition
tup1 = ('Geeks',) * 3
print(tup1)
# Creating a Tuple with the use of loop
tup = ('Geeks')
n=5
for i in range(int(n)):
tup = (tup,)
print(tup)
Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
((((('Geeks',),),),),)
Python Tuple Basic Operations
Below are the Python tuple operations.
Accessing of Python Tuples
Concatenation of Tuples
Slicing of Tuple
Deleting a Tuple
Accessing of Tuples
We can access the elements of a tuple by using indexing
and slicing, similar to how we access elements in a list. Indexing
starts at 0 for the first element and goes up to n-1, where n is
the number of elements in the tuple. Negative indexing starts
from -1 for the last element and goes backward.
Example:
# Accessing Tuple with Indexing
tup = tuple("Geeks")
print(tup[0])
# Accessing a range of elements using slicing
print(tup[1:4])
print(tup[:3])
# Tuple unpacking
tup = ("Geeks", "For", "Geeks")
# This line unpack values of Tuple1
a, b, c = tup
print(a)
print(b)
print(c)
Output
G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks
Concatenation of Tuples
Tuples can be concatenated using the + operator. This operation combines two or more tuples
to create a new tuple.
tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')
tup3 = tup1 + tup2
print(tup3)
Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Slicing of Tuple
Slicing a tuple means creating a new tuple from a subset of elements of the original tuple.
The slicing syntax is tuple[start:stop:step].
tup = tuple('GEEKSFORGEEKS')
# Removing First element
print(tup[1:])
# Reversing the Tuple
print(tup[::-1])
# Printing elements of a Range
print(tup[4:9])
Output
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
('S', 'F', 'O', 'R', 'G')
Deleting a Tuple
Since tuples are immutable, we cannot delete individual elements of a tuple. However, we
can delete an entire tuple using del statement.
tup = (0, 1, 2, 3, 4)
del tup
print(tup)
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 6, in <module>
NameError: name 'tup' is not defined
uple Unpacking with Asterisk (*)
In Python, the " * " operator can be used in tuple unpacking to grab multiple items into a list.
This is useful when you want to extract just a few specific elements and collect the rest
together.
tup = (1, 2, 3, 4, 5)
a, *b, c = tup
print(a)
print(b)
print(c)
Output
1
[2, 3, 4]
5
Explanation:
a gets the first item.
c gets the last item.
b collects everything in between into a list.
Differences between List and Tuple
Tuple Built-in functions:
len(): Returns the number of elements in the tuple.
min(): Returns the smallest item in the tuple (if elements are comparable).
max(): Returns the largest item in the tuple (if elements are comparable).
sum(): Returns the sum of all numeric items in the tuple.
sorted(): Returns a new list containing all items from the tuple in sorted order.
tuple(): Converts an iterable (like a list or string) into a tuple.
Methods:
Python tuples, being immutable sequences, offer a limited set of built-in methods compared
to mutable data structures like lists. The primary methods available for tuples are:
count(): This method returns the number of times a specified value appears within the
tuple.
Python
my_tuple = (1, 2, 2, 3, 4, 2)
count_of_2 = my_tuple.count(2)
print(f"Count of 2: {count_of_2}") # Output: Count of 2: 3
index(): This method returns the index of the first occurrence of a specified value
within the tuple. If the value is not found, it raises a ValueError.
Python
my_tuple = ('apple', 'banana', 'cherry', 'apple')
index_of_banana = my_tuple.index('banana')
print(f"Index of 'banana': {index_of_banana}") # Output: Index of 'banana': 1
Dictionaries in Python
Dictionaries in Python are a built-in data structure used to store data in key-value pairs. They
are also known as hash maps or associative arrays in other programming languages.
Key Characteristics:
Key-Value Pairs:
Each item in a dictionary consists of a unique key mapped to a corresponding value.
Ordered (Python 3.7+):
Dictionaries maintain the insertion order of items. In Python versions prior to 3.7, dictionaries
were unordered.
Changeable (Mutable):
You can add, remove, or modify key-value pairs after a dictionary is created.
No Duplicate Keys:
Each key within a dictionary must be unique. If a key is repeated, the later value associated
with that key will overwrite the previous one.
Keys Must Be Immutable:
Dictionary keys must be of an immutable data type, such as strings, numbers, or
tuples. Values, however, can be of any data type.
Creating Dictionaries:
Dictionaries are created using curly braces {} with key-value pairs separated by colons : and
individual pairs separated by commas ,.
Python
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
Accessing Values:
Values are accessed using their corresponding keys within square brackets [].
Python
print(my_dict["name"]) # Output: Alice
Adding/Updating Items:
New key-value pairs can be added, or existing ones updated, by assigning a value to a key.
Python
my_dict["occupation"] = "Engineer" # Add a new item
my_dict["age"] = 31 # Update an existing item
Removing Items:
Items can be removed using the del keyword or methods like pop() and popitem().
Python
del my_dict["city"]
removed_value = my_dict.pop("age")
Common Dictionary Methods:
keys(): Returns a view object of all keys.
values(): Returns a view object of all values.
items(): Returns a view object of all key-value pairs as tuples.
get(key, default): Retrieves the value for a given key, returning None or a
specified default if the key is not found.
update(other_dict): Adds or updates key-value pairs from another dictionary.
Set
In Python, a set is an unordered collection of unique elements. This means:
Unique Elements:
A set cannot contain duplicate items. If you try to add a duplicate, it will be ignored.
Unordered:
Elements within a set do not have a defined order, and their order may change. You cannot
access elements by index like in lists or tuples.
Mutable (generally):
You can add or remove elements from a set after it has been created.
Defined by curly braces or set() constructor:
Sets are typically created by enclosing comma-separated elements within curly braces {} or
by using the set() built-in function with an iterable.
Creating a Set:
Python
# Using curly braces
my_set = {1, 2, 3, 4}
# Using the set() constructor with an iterable (e.g., a list)
another_set = set([5, 6, 7, 8])
# An empty set must be created using set()
empty_set = set()
Common Set Operations:
Adding elements:
add() method for a single element, update() method for multiple elements from another
iterable.
Removing elements:
remove() (raises error if element not found), discard() (no error if element not
found), pop() (removes and returns an arbitrary element), clear() (removes all elements).
Mathematical Set Operations:
Union: union() or | operator (elements in either set).
Intersection: intersection() or & operator (elements common to both sets).
Difference: difference() or - operator (elements in the first set but not the
second).
Symmetric Difference: symmetric_difference() or ^ operator (elements in
either set but not in both).
Use Cases:
Removing duplicates from a sequence: Convert a list or tuple to a set to
automatically eliminate duplicates.
Membership testing: Efficiently check if an element is present in a collection.
Performing mathematical set operations.