Python_Track-DS_Basics(Lists_and_Tuples)
Python_Track-DS_Basics(Lists_and_Tuples)
● Lists can be created using square brackets [] and separating items with
commas.
● The list() constructor can also be used to create lists.
nums = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# Extracting a sublist from index 2 to index 4
nums[-4 : -1] ??
Modifying Lists
● Lists are mutable, allowing you to change their contents.
● You can modify items using their index or extend the list using append()
and insert().
● You can also remove items using remove() and pop().
Examples
fruits = ["apple", "banana", "cherry"]
# Changing the first item
fruits[0] = "orange" # fruits = ["orange", "banana", "cherry"]
# Adding an item to the end
fruits.append("mango") # fruits = ["orange", "banana", "cherry", "mango"]
# Removing an item by value
fruits.remove("cherry") # fruits = ["orange", "banana", "mango"]
# Removing the last item
removed_item = fruits.pop() # removed_item = "mango", fruits =
["orange", "banana"]
Common List Operations
● Checking if an item exists: in keyword
● Sorting a list: sort() method
● sorted ( nums , key = myFunction ( ), reverse = True/False)
● Reversing a list: reverse() method
Examples
fruits = ["orange", "banana"]
# Checking if "orange" exists in the list
if "orange" in fruits:
print("Yes, orange is in the list")
# Sorting the list in ascending order
fruits.sort() # fruits = ["banana", "orange"]
# Reversing the sorted list
fruits.reverse() # fruits = ["orange", "banana"]
Combining Lists
● Concatenating lists using the + operator or extend() method
● Adding items from one list to another individually
Examples
numbers = [1, 2, 3]