
![]() |
@wtf | |
(Filter odd/even numbers easily) |
||
2
Replies
13
Views
1 Bookmarks
|
![]() |
@wtf | 1 day 6 hours |
* List Comprehensions in Python* A list comprehension is a concise way to create lists by applying an expression to each item in an iterable. *Basic Syntax* : [expression for item in iterable if condition] *Example 1: Square All Numbers* nums = [1, 2, 3, 4] squares = [x**2 for x in nums] print(squares) Output: [1, 4, 9, 16] *Example 2: Filter Even Numbers* nums = [1, 2, 3, 4, 5, 6] evens = [x for x in nums if x % 2 == 0] print(evens) Output: [2, 4, 6] *Example 3: Convert Strings to Uppercase* names = [alice, bob, charlie] upper_names = [name.upper() for name in names] print(upper_names) Output: ['ALICE', 'BOB', 'CHARLIE'] *Equivalent Using Loops:* squares = [] for x in nums: squares.append(x**2) List comprehensions are faster, cleaner, and more readable when used correctly. *Mini Project: Filter Odd Numbers and Cube Them* nums = list(range(1, 11)) odd_cubed = [x**3 for x in nums if x % 2 != 0] print(Cubes of odd numbers from 1 to 10:, odd_cubed) *This shows:* - Filtering (odds only) - Transformation (cubing) - Compact, readable logic |
||
![]() |
@julyjlk | 1 day 6 hours |
please, bro, on example 1. ** stand for (power).? or.
|
||


