DeveloperBreeze

This cheatsheet provides a comprehensive guide to common list operations in Python, including how to remove empty items, add or remove elements, and perform slicing, sorting, and more.


1. Removing Empty Items from a List

You can use either list comprehension or the filter() function to remove empty items from a list.

Using List Comprehension:

my_list = ["apple", "", "banana", "", "cherry", ""]
my_list = [item for item in my_list if item]
print(my_list)  # Output: ['apple', 'banana', 'cherry']

Using filter():

my_list = ["apple", "", "banana", "", "cherry", ""]
my_list = list(filter(None, my_list))
print(my_list)  # Output: ['apple', 'banana', 'cherry']

2. Adding Items to a List

Append an item to the end of the list:

my_list = ["apple", "banana"]
my_list.append("cherry")
print(my_list)  # Output: ['apple', 'banana', 'cherry']

Insert an item at a specific position:

my_list = ["apple", "banana"]
my_list.insert(1, "cherry")
print(my_list)  # Output: ['apple', 'cherry', 'banana']

Extend a list with another list:

my_list = ["apple", "banana"]
my_list.extend(["cherry", "orange"])
print(my_list)  # Output: ['apple', 'banana', 'cherry', 'orange']

3. Removing Items from a List

Remove an item by value:

my_list = ["apple", "banana", "cherry"]
my_list.remove("banana")
print(my_list)  # Output: ['apple', 'cherry']

Remove an item by index:

my_list = ["apple", "banana", "cherry"]
my_list.pop(1)
print(my_list)  # Output: ['apple', 'cherry']

Clear all items from the list:

my_list = ["apple", "banana", "cherry"]
my_list.clear()
print(my_list)  # Output: []

4. Slicing a List

Get a sublist by slicing:

my_list = ["apple", "banana", "cherry", "orange", "kiwi"]
sub_list = my_list[1:4]
print(sub_list)  # Output: ['banana', 'cherry', 'orange']

Get the last three items of the list:

my_list = ["apple", "banana", "cherry", "orange", "kiwi"]
print(my_list[-3:])  # Output: ['cherry', 'orange', 'kiwi']

5. Sorting a List

Sort a list in ascending order:

my_list = [3, 1, 4, 1, 5, 9]
my_list.sort()
print(my_list)  # Output: [1, 1, 3, 4, 5, 9]

Sort a list in descending order:

my_list = [3, 1, 4, 1, 5, 9]
my_list.sort(reverse=True)
print(my_list)  # Output: [9, 5, 4, 3, 1, 1]

Sort a list of strings alphabetically:

my_list = ["banana", "apple", "cherry"]
my_list.sort()
print(my_list)  # Output: ['apple', 'banana', 'cherry']

Sort a list without modifying the original list:

my_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 1, 3, 4, 5, 9]

6. Checking for Items in a List

Check if an item exists in a list:

my_list = ["apple", "banana", "cherry"]
print("banana" in my_list)  # Output: True

Get the index of an item:

my_list = ["apple", "banana", "cherry"]
index = my_list.index("banana")
print(index)  # Output: 1

7. List Comprehension

Basic list comprehension:

squared = [x**2 for x in range(5)]
print(squared)  # Output: [0, 1, 4, 9, 16]

Conditional list comprehension:

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # Output: [0, 2, 4, 6, 8]

8. Combining Lists

Concatenate two lists:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # Output: [1, 2, 3, 4, 5, 6]

Zip two lists into pairs:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
zipped = list(zip(list1, list2))
print(zipped)  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]

9. Other Useful List Operations

Get the length of a list:

my_list = ["apple", "banana", "cherry"]
print(len(my_list))  # Output: 3

Count occurrences of an item:

my_list = ["apple", "banana", "cherry", "banana"]
print(my_list.count("banana"))  # Output: 2

Reverse a list:

my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list)  # Output: [4, 3, 2, 1]

10. Copying Lists

Shallow copy a list:

my_list = ["apple", "banana", "cherry"]
copy_list = my_list.copy()
print(copy_list)  # Output: ['apple', 'banana', 'cherry']

Conclusion

This Python list operations cheatsheet covers a wide range of list methods and functionalities. Whether you're adding, removing, slicing, or sorting, Python's list methods are intuitive and powerful. Use this guide as a quick reference for your day-to-day Python programming tasks involving lists.

Continue Reading

Discover more amazing content handpicked just for you

Code
python

Convert Words to Uppercase in List Comprehension

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Calculate Sum of Numbers in a List Using sum() Function

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Generate List of Even Numbers Using List Comprehension

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Find Maximum Number in List Using max() Function

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!