Python Slicing Comprehensions Sorting

Python: Slicing, Comprehensions & Sorting 1. List & String Slicing Slicing helps you extract parts of a sequence. List Example: nums = [10, 20, 30, 40, 50] print(nums[1:4]) # Output: [20, 30, 40] String Example: text = "Python" print(text[::-1]) # Output: nohtyP (reverse string) --- 2. List, Set & Dictionary Comprehension Clean, fast, and Pythonic way to create collections. List Comprehension: squares = [x**2 for x in range(5)] [0, 1, 4, 9, 16] Set Comprehension: unique = {x for x in [1, 2, 2, 3]} {1, 2, 3} Dictionary Comprehension: square_dict = {x: x**2 for x in range(3)} {0:0, 1:1, 2:4} --- 3. Sorting List, Tuple & Objects Sorting List: nums = [3, 1, 4, 2] print(sorted(nums)) # [1, 2, 3, 4] nums.sort(reverse=True) # [4, 3, 2, 1] Sorting Tuple: t = (5, 2, 8, 1) print(sorted(t)) # [1, 2, 5, 8] Sorting Objects: students = [ {"name": "A", "marks": 85}, {"name": "B", "marks": 92} ] sorted_students = sorted(students, key=lambda x: x["marks"]) #Python #DataAnalytics #Coding #Programming #LearnPython #100DaysOfCode #Developer

To view or add a comment, sign in

Explore content categories