2.1 Lists: Lists are used to store multiple items in a single variable.
- List can contain duplicate items.
- List in Python are Mutable. Hence, we can modify, replace or delete the items.
- List are ordered. It maintains the order of elements based on how they are added.
- Accessing items in List can be done directly using their position (index), starting from 0.
· You can create a list using square brackets [] or the list() constructor.
fruits = ["apple", "banana", "cherry"]
# Using square bracketsmy_list = [1, 2, 3, 4, 5]# Using list()another_list = list(("Palak", "Methi", "Tomato")) # Notice the double parentheses# Lists can contain different data typesmixed_list = [1, "hello", 3.14, True]thislist = ["apple", "banana", "cherry"]
print(len(thislist)) #Print the number of items in the list
The list() Constructor: It is also possible to use the list() constructor when creating a new list. Example Using the list() constructor to make a List: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist)
Accessing the listprint(my_list[0]) # Output: 10 (first element) print(my_list[-1]) # Output: 50 (last element)type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))Creating List with Repeated Elements We can create a list with repeated elements using the multiplication operator. # Create a list [2, 2, 2, 2, 2] a = [2] * 5 # Create a list [0, 0, 0, 0, 0, 0, 0] b = [0] * 7 print(a) print(b) Adding Elements into List We can add elements to a list using the following methods: append(): Adds an element at the end of the list. extend(): Adds multiple elements to the end of the list. insert(): Adds an element at a specific position. Updating Elements into List We can change the value of an element by accessing it using its index. a = [10, 20, 30, 40, 50] # Change the second element a[1] = 25 print(a) Removing Elements from List We can remove elements from a list using: remove(): Removes the first occurrence of an element. pop(): Removes the element at a specific index or the last element if no index is specified.
del statement: Deletes an element at a specified index.
clear()- Removes all elements from the list. a = [10, 20, 30, 40, 50] # Removes the first occurrence of 30 a.remove(30) print("After remove(30):", a) # Removes the element at index 1 (20) popped_val = a.pop(1) print("Popped element:", popped_val) print("After pop(1):", a) # Deletes the first element (10) del a[0] print("After del a[0]:", a)
Searching and Indexing
index(item, start, end)- Returns the index of the first occurrence of an item within a specific range.count(item)- Counts how many times an item appears in the list.a = ["cat", "dog", "tiger"] print(a.index("dog")) Sorting and Reversing
sort(key=None, reverse=False) - Sorts the list in place (ascending by default).
reverse() - Reverses the elements of the list in place.
a = [1, 2, 3, 4, 5]
# Reverse the list in-place
a.reverse()
print(a)
Copying
copy() - Returns a shallow copy of the list.thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)Iterating Over Lists :
Using for Loop
a = ['apple', 'banana', 'cherry'] # Iterating over the list for item in a: print(item)
- General Functions
len(list)- Returns the number of items in the list.max(list)- Returns the maximum value in the list.min(list)- Returns the minimum value in the list.sum(list)- Returns the sum of elements (numeric).sorted(list, key=None, reverse=False)- Returns a new sorted list.reversed(list)- Returns an iterator that accesses the list in reverse order.enumerate(list)- Returns an iterator of index-value pairs.all(list)- ReturnsTrueif all elements are truthy.any(list)- ReturnsTrueif at least one element is truthy.
Type Conversion
list(iterable)- Converts an iterable (e.g., tuple, string) into a list.
Example Usage
# List methods
my_list = [3, 1, 4, 1, 5]
my_list.append(9) # [3, 1, 4, 1, 5, 9]
my_list.sort() # [1, 1, 3, 4, 5, 9]
# Built-in functions
print(len(my_list)) # 6
print(max(my_list)) # 9
print(sum(my_list)) # 23
print(sorted(my_list)) # [1, 1, 3, 4, 5, 9]
To Swap Two Elements in a List
a = [10, 20, 30, 40, 50]
# Swapping elements at index 0 and 4
# using multiple assignment
a[0], a[4] = a[4], a[0]
print(a)
Check if element exists in list in Python
a = [10, 20, 30, 40, 50]
# Check if 30 exists in the list
if 30 in a:
print("Element exists in the list")
else:
print("Element does not exist")
Using any()
The any() function is used to check if any element in an iterable evaluates to True.
It returns True if at least one element in the iterable is truthy
(i.e., evaluates to True), otherwise it returns False
a = [10, 20, 30, 40, 50]
# Check if 30 exists using any() function
flag = any(x == 30 for x in a)
if flag:
print("Element exists in the list")
else:
print("Element does not exist")
Ways to remove duplicates from list in Python Using set() We can use set() to remove duplicates from the list. However, this approach does not preserve the original order. a = [1, 2, 2, 3, 4, 4, 5] # Remove duplicates by converting to a set a = list(set(a)) print(a) Merge Two Lists in Python a = [1, 2, 3] b = [4, 5, 6] # Merge the two lists and assign # the result to a new list c = a + b print(c)
List Methods
| Method | Description |
|---|---|
| append() | Adds an element at the end of the list |
| clear() | Removes all the elements from the list |
| copy() | Returns a copy of the list |
| count() | Returns the number of elements with the specified value |
| extend() | Add the elements of a list (or any iterable), to the end of the current list |
| index() | Returns the index of the first element with the specified value |
| insert() | Adds an element at the specified position |
| pop() | Removes the element at the specified position |
| remove() | Removes the item with the specified value |
| reverse() | Reverses the order of the list |
| sort() | Sorts the list |
No comments:
Post a Comment