[Link]
org/python/python-built-in-functions/
[Link]
Python list comprehension provides a concise and efficient way to create new
lists based on existing iterables (like lists, tuples, strings, ranges, etc.). It offers
a more readable and often faster alternative to traditional for loops for list
creation and manipulation.
new_list = [expression for item in iterable if condition]
Creating a list of squares
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
# squares will be [1, 4, 9, 16, 25]
Filtering even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
# even_numbers will be [2, 4, 6, 8, 10]
Applying a conditional expression
prices = [1.25, -9.45, 10.22, 3.78, -5.92]
adjusted_prices = [price if price > 0 else 0 for price in prices]
# adjusted_prices will be [1.25, 0, 10.22, 3.78, 0]
String:
[Link]
Lists:
[Link]
In Python, a list is a built-in dynamic sized array (automatically grows and
shrinks). We can store all types of items (including another list) in a list. A list
may contain mixed type of items, this is possible because a list mainly stores
references at contiguous locations and actual items may be stored at
different locations.
● List can contain duplicate items.
● List in Python are Mutable. Hence, we can modify, replace or delete
the items.
● List are ordered. It maintains the order of elements based on how
they are added.
● Accessing items in List can be done directly using their position
(index), starting from 0.
Syntax of sort() method
list_name.sort(key=None, reverse=False)
Parameter:
● key (Optional): This is an optional parameter that allows we to
specify a function to be used for sorting. For example, we can use
the len() function to sort a list of strings based on their length.
● reverse (Optional): This is an optional Boolean parameter. By
default, it is set to False to sort in ascending order. If we set
reverse=True, the list will be sorted in descending order.
a = [5, 2, 9, 1, 5, 6]
# Sorting in Descending Order
[Link](reverse=True)
print(a)
[Link]
Python lambda functions:
[Link]
lter-map-reduce/