Python Lists: A Comprehensive Guide

Lists in Python A versatile data structure used to store multiple items in a single variable. 🎯 1. What is a List? Lists are ordered, mutable collections of items that allow duplicate elements. They are defined using square brackets []. 🎯 2. Creating a List A list by placing comma-separated values inside square brackets. python # Example my_list = [1, "Hello", 3.14, True] 🎯 3. Accessing List Elements & Indexing zero-based indexing to access elements. python # Example fruits = ["apple", "banana", "cherry"] print(fruits[0]) # First element print(fruits[-1]) # Last element 🎯 4. List Slicing Access a range of elements Syntax [start:stop:step]. python # Example numbers = [10, 20, 30, 40, 50, 60] print(numbers[1:4]) # From index 1 up to (but not including) 4 print(numbers[::-1]) # Reverse the list Output: [20, 30, 40] [60, 50, 40, 30, 20, 10] 🎯 5. Modifying Lists Lists are mutable, meaning you can change their items. python # Example fruits = ["apple", "banana", "cherry"] fruits[1] = "blueberry" # Change index 1 print(fruits) Output: [apple, blueberry, cherry] 🎯 6. List Methods append() : Adds an item to the end. python fruits.append("orange") insert() : Adds an item at a specific position. python fruits.insert(1, "mango") remove() : Removes the first occurrence of a specific value. python fruits.remove("banana") pop() : Removes and returns an item at a specific index (or the last item if no index is specified). python last_item = fruits.pop() sort() : Sorts the list in place. 🎯 List Comprehensions A list comprehension offers a concise way to create lists in Python based on existing lists or iterables. Basic Syntax: new_list = [expression for item in iterable if condition] 🎯 1. Creating a List of Squares Instead of using a for loop to append squares, you can do it in one line. python # Traditional loop squares = [] for x in range(1, 6): squares.append(x*2) 🎯 List comprehension squares = [x*2 for x in range(1, 6)] print(squares) Output: [1, 4, 9, 16, 25] 🎯 2. Filtering with if Condition You can add a condition to filter elements from the original list. python numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Get only even numbers evens = [x for x in numbers if x % 2 == 0] print(evens) Output: [2, 4, 6, 8, 10] 🎯 3. Transforming Strings You can apply string methods like .upper() during creation. python fruits = ["apple", "banana", "cherry"] # Convert all to uppercase upper_fruits = [fruit.upper() for fruit in fruits] print(upper_fruits) Output: ['APPLE', 'BANANA', 'CHERRY'] 🎯 4. Flattening a Nested List This is a highly efficient way to turn a list of lists into a single flat list. python nested_list = [[1, 2], [3, 4], [5, 6]] # Flatten the list flatlist = [item for sublist in nestedlist for item in sublist] print(flat_list) Output: [1, 2, 3, 4, 5, 6] #PythonProgramming #PythonList #DataScience #CodingTips #PythonTutorial #SoftwareDevelopment #Programming

To view or add a comment, sign in

Explore content categories