LIST
A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. This is easy to imagine if you can think of a shopping list where you have a list of items to buy, except that you probably have each item on a separate line in your shopping list whereas in Python you put commas in between them. The list of items should be enclosed in square brackets so that Python understands that you are specifying a list. Once you have created a list, you can add, remove or search for items in the list. Since we can add and remove items, we say that a list is a mutable data type i.e. this type can be altered.
Properties of List
- Ordered collection of data
- Data can be of different types
- Lists are mutable
- Issues with shared references and mutability
- Same subset operations as Strings
INBUILT FUCTIONS
Method |
Description |
Example |
append() |
Adds an element at the end of the list |
thislist.append(“orange") |
clear() |
Removes all the elements from the list |
thislist.clear() |
copy() |
Returns a copy of the list |
x = fruits.copy() |
count() |
Returns the number of elements with the specified value |
x = fruits.count(“cherry") |
extend() |
Add the elements of a list (or any iterable), to the end of the current list |
fruits.extend(cars) |
index() |
Returns the index of the first element with the specified value |
x = fruits.index(“cherry") |
insert() |
Adds an element at the specified position |
fruits.insert(1, “orange") |
pop() |
Removes the element at the specified position |
fruits.pop(1) |
remove() |
Removes the item with the specified value |
fruits.remove(“banana") |
reverse() |
Reverses the order of the list |
fruits.reverse() |
sort() |
Sorts the list |
fruits.sort() |
BASIC LIST OPERATORS
Expression |
Results |
Description |
len([1, 2, 3]) |
3 |
Length |
[1, 2, 3] + [4, 5, 6] |
[1, 2, 3, 4, 5, 6] |
Concatenation |
['Hi!'] * 4 |
['Hi!', 'Hi!', 'Hi!', 'Hi!'] |
Repetition |
3 in [1, 2, 3] |
True |
Membership |
for x in [1, 2, 3]: print x, |
1 2 3 |
Iteration |
Programs to Practice
#Collection - it can store more than 1 value OUTPUT: |
List Functions |
LAMBDA
lambda operator or lambda function is used for creating small, one-time and anonymous function objects in Python.
Basic Syntax: lambda arguments : expression
lambda operator can have any number of arguments, but it can have only one expression. It cannot contain any statements and it returns a function object which can be assigned to any variable.
LAMBDA Programs in the Class
#Normal Way of Writing Function:
def power(x, y):
return x ** y
# Call the function
a =power(2, 3)
print(a)
#Function using Lambda Operator:
add = lambda x, y: x ** y
a = add(2, 3)
print(a)
LIST FUNCTIONS
These are three functions which facilitate a functional approach to programming. We will discuss them one by one and understand their use cases:
- Map
- Filter
- Reduce
Map
- We spend lot of time analyzing list of data like: List of stock prices, Orders, Customer profiles
- Map applies a function to all the items in an input_list
- map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
Problem Blueprint:
Data: a1, a2, … ,an
Function: f
map(f, data) returns Iterator over: f(a1), f(a2), …, f(an)
Blueprint
map(function_to_apply, list_of_inputs)
Most of the times we want to pass all the list elements to a function one-by-one and then collect the output.
MAPS Programs
#Program without Maps
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
print(squared)
#Map allows us to implement this in a much simpler and nicer way. Here you go
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
def multiply(x):
return (x * x)
def add(x):
return (x + x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
Filter
As the name suggests, filter creates a list of elements for which a function returns true. It filters out the data you do not need. E.g. Find all data above average
The filter resembles a for loop but it is a builtin function and faster.
Here is a short and concise example:
FILTER Programs
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
import statistics
data_list = [5, 1, 8,2,5,9,12,15,18]
avg_val = statistics.mean (data_list)
above_avg = list(filter(lambda x: x > avg_val, data_list))
print(above_avg)
#Another example, to filter out missing data
states = ["","Telangana", "","Bihar", "","Goa", "","","","Rajasthan", "",""]
final_list = list(filter(None, states))
print(final_list)
Reduce
- Reduce is a really useful function for performing some computation on a list and returning the result.
- It applies a rolling computation to sequential pairs of values in a list.
- For example, if you wanted to compute the product of a list of integers.
- Normal way you might go about doing this task in python is using a basic for loop
- In Python 3, it is no longer a built-in function, we need to call from functools.reduce()
How it works
Data: [a1, a2, a3, …, an]
Function: f(x,y)
reduce (f,data):
Step 1: val1 = f(a1,a2)
Step 2: val2 = f(val1,a3)
Step 3: val3 = f(val2,a4)
…
Step n-1: valn-1 = f(valn-2,an)
Return Valn-1
i.e. Reduce: f ( f ( f ( a1,a2), a3), … , an)
REDUCE Programs
# Without Reduce
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
print("Without Reduce concept, output: ", product)
# product = 24
#Now let’s try it with reduce: same logic
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print("Now with Reduce, output: ", product)
Assignments
- Write a Python program to sum all the items in a list.
- Write a Python program to multiplies all the items in a list.
- Write a Python program to get the largest number from a list.
- Write a Python program to get the smallest number from a list.
- Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.
Sample List : ['abc', 'xyz', 'aba', '1221’]
Expected Result : 2
- Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
- Write a Python program to remove duplicates from a list.
- Write a Python program to check a list is empty or not.
- Write a Python program to clone or copy a list.
- Write a Python program to find the list of words that are longer than n from a given list of words.
- Write a Python function that takes two lists and returns True if they have at least one common member.
- Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow’]
Expected Output : ['Green', 'White', 'Black']
- Write a Python program to generate a 3*4*6 3D array whose each element is *.
- Write a Python program to print the numbers of a specified list after removing even numbers from it.
- Write a Python program to shuffle and print a specified list.
- Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).
- Write a Python program to generate and print a list except for the first 5 elements, where the values are square of numbers between 1 and 30 (both included).
- Write a Python program to generate all permutations of a list in Python.
- Write a Python program to get the difference between the two lists.
- Write a Python program access the index of a list.