Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Python Programming Tutorial

Day 12
Agenda
1) Looping in Lists
2) Difference between List and Tuple
3) List Comprehension

Looping in List
Looping through a list is a fundamental programming concept that allows you to
iterate over each element in the list and perform some action on it. Here are
some examples in Python:

1. Printing each element in a list:


my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
2. Summing up all elements in a list:
my_list = [1, 2, 3, 4, 5]
total = 0
for item in my_list:
total =total+item
print("Sum of all elements:", total)
3. Finding the maximum element in a list:
my_list = [1, 7, 3, 9, 5]
max_value = my_list[0]
for item in my_list:
if item > max_value:
max_value = item
print("Maximum value:", max_value)

4. Checking for specific conditions in a list:


my_list = [10, 20, 30, 40, 50]
for item in my_list:
if item % 2 == 0:
print(item, "is even")
else:
print(item, "is odd")

40
Difference Between List and Tuple

S_no LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations


2
consuming is comparatively Faster

The list is better for performing A Tuple data type is


3 operations, such as insertion and appropriate for accessing the
deletion. elements

Tuple consumes less memory


4 Lists consume more memory
as compared to the list

Tuple does not have many


5 Lists have several built-in methods
built-in methods.

Unexpected changes and errors are Because tuples don’t change


6
more likely to occur they are far less error-prone.

List Comprehension
List comprehension is a concise way to create lists in Python. It allows you to
construct a new list by iterating over an existing iterable (such as a list, tuple, or
range) and applying an expression to each element. Here are some examples:

1. Creating a list of squares:


squares = [x**2 for x in range(1, 6)]
print(squares)
# Output: [1, 4, 9, 16, 25]
2. Filtering elements with a condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
# Output: [2, 4, 6, 8, 10]

List comprehensions offer a concise and readable way to create lists in Python,
often replacing loops and conditional statements with a single line of code.
41

You might also like