List Operations in Python
Logical Operations with Lists
• Membership operators:
o is / is not
o in / not in
• Logical operators:
o and / or / not
Creating and Modifying Lists
1. Using the list() constructor:
o Use the list() function to create a new list.
2. Adding Elements:
o To add an item at the end:
▪ Use the append() method.
o To insert an item at a specific index:
▪ Use the insert() method.
▪ Example:
▪ thislist = ["apple", "banana", "cherry"]
▪ thislist.insert(2, "watermelon")
▪ print(thislist)
o To append elements from another list:
▪ Use the extend() method.
▪ Example:
▪ list1.extend(list2)
3. Removing Elements:
o Remove an item by value: Use the remove() method.
o Remove an item by index:
▪ Use the pop() method.
▪ Use the del keyword.
o Delete the entire list: Use the del keyword.
o Clear all elements: Use the clear() method (the list remains but is empty).
Copying Lists
• Built-in methods:
o Use the copy() method.
• Other techniques:
o Use the list() constructor.
o Use slicing (: operator).
o Example:
o mylist = thislist[:]
Sorting and Reversing Lists
1. Sorting:
o Use the sort() method (alphanumeric or numeric, ascending by default).
o To sort in descending order:
▪ Use reverse=True as a keyword argument.
o For case-insensitive sorting:
▪ Use key=str.lower.
2. Reversing:
o Use the reverse() method to reverse the order of elements.