0% found this document useful (0 votes)
28 views13 pages

List-Tuple and Sets

Uploaded by

ahmadmian1551
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views13 pages

List-Tuple and Sets

Uploaded by

ahmadmian1551
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

List
An ordered, mutable (changeable) collection that can contain a variety of data types is called a list
in Python. You can store integers, texts, floats, or even other lists with lists, which are defined with
square brackets [].

Syntax
Empty list
my_list = []

List with integers


numbers = [1, 2, 3, 4, 5]

List with strings


fruits = ["apple", "banana", "cherry"]

Mixed list
mixed = [1, "hello", 3.14, True]

Nested list (list inside a list)


nested = [[1, 2], ["a", "b"], [True, False]]

List slicing
With Python's list slicing feature, you may specify a range of indices for finding particular parts
of a list. The fundamental slicing syntax is:
new_list = my_list[start:stop:step]
my_list = [10, 20, 30, 40, 50, 60, 70]
 my_list[1:4]
 my_list[:3]
 my_list[3:]
 my_list[0:7:2]
 my_list[-5:-2]
 my_list[::-1]

21
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

List concatenation
In Python, list concatenation enables you to merge two or more lists into one. Here are a few
methods for doing it:

Using the + Operator


list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]

List with Repeated Elements


Use the * operator to repeat a list or element multiple times:
# Repeat the list 3 times
repeated_list = [1, 2, 3] * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
# Repeat a single element multiple time
single_element_repeated = [5] * 4
print(single_element_repeated) # Output: [5, 5, 5, 5]

Built-in functions for List


Function Description Example
len(list) Returns the number of len([1, 2, 3]) → 3
elements in the list.
sum(list) Returns the sum of all sum([1, 2, 3]) → 6
elements in a list of numbers.
min(list) Returns the smallest element min([3, 1, 2]) → 1
in the list.
max(list) Returns the largest element in max([3, 1, 2]) → 3
the list.
sorted(list) Returns a new sorted list sorted([3, 1, 2]) → [1, 2, 3]
without changing the original
list.

22
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

list.sort() Sorts the list in place, meaning my_list = [3, 1, 2]


it modifies the original list. my_list.sort()
print(my_list) → [1, 2, 3]
list.sort(reverse=True)
list.append(x) Adds an element x to the end my_list.append(4)
of the list.
list.insert(i, x) Inserts an element x at index i my_list.insert(1, "apple")
in the list.
list.remove(x) Removes the first occurrence my_list.remove("apple")
of element x in the list.
list.pop(i) Removes and returns the my_list.pop()
element at index i; if i is not or
specified, it removes the last my_list.pop(2)
item.
list.clear() Removes all elements from my_list.clear()
the list, making it empty.
list.index(x) Returns the index of the first my_list.index("apple")
occurrence of element x.
list.count(x) Returns the number of times x my_list.count(2)
appears in the list.
list.extend(iterable) Adds all elements from an my_list.extend([4, 5, 6])
iterable (like another list) to
the end of the list.
reversed(list) Returns an iterator that list(reversed([1, 2, 3])) → [3,
accesses the list in reverse 2, 1]
order. An iterator is an object
in Python that allows you to
traverse through a sequence. It
enables you to iterate over the
elements without needing to
know how the data is stored
internally.
any(list) Returns True if any element in any([0, False, 3]) → True
the list is True; otherwise,
False. (non-zero numbers)
all(list) Returns True if all elements in all([1, True, 3]) → True
the list are True; otherwise,
False.

List in-operator
It is usual practice to traverse over the list's elements and perform operations on them by using a
list in a for loop. The following explains how lists can be used in for loops:
my_list = [1, 2, 3, 4, 5]

23
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

for number in my_list:


print(number)

Let’s practice
Task
1. Create an empty list and print it.
2. Create a list with integers from 1 to 10 and print it.
3. Create a list with mixed data types (e.g., integer, string, float, boolean) and print it.
4. Create a nested list (a list inside a list) and print it.
5. Given a list my_list = [10, 20, 30, 40, 50, 60, 70], perform the following slicing operations:
a. my_list[1:4]
b. my_list[:3]
c. my_list[3:]
d. my_list[0:7:2]
e. my_list[-5:-2]
f. my_list[::-1]
6. Concatenate two lists: list1 = [1, 2, 3] and list2 = [4, 5, 6] and print the result.
7. Repeat the list [1, 2, 3] 3 times and print the result.
8. Repeat element [5] four times and print the result.
9. Create a list_numbers = [10, 20, 30, 40, 50] and perform the following operations:
a. Find the length of the list using len().
b. Calculate the sum of the list using sum().
c. Find the minimum and maximum values using min() and max().
d. Sort the list using sorted() and print the sorted list.
e. Find the index of an element using index().
f. Count how many times an element appears in the list using count().
g. Add an element to the end of the list using append().
h. Insert an element at a specific index using insert().

24
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

i. Remove an element using remove().


j. Pop an element using pop().
k. Clear all elements using clear().
10. Use a for loop to iterate through the list [1, 2, 3, 4, 5] and print each element.
11. Modify the list [1, 2, 3, 4, 5] by multiplying each element by 2 inside a loop and print the
modified list.
12. Write a for loop that prints only the even numbers from the list [1, 2, 3, 4, 5, 6].
13. Write a for loop that appends only positive numbers from a mixed list [1, -2, 3, -4, 5] to a
new list.
14. Access elements inside a nested list, e.g., nested = [[1, 2], ["a", "b"], [True, False]], and
print each inner list.
15. Write a program that checks if any element in the list [0, False, 3] is True using any().
16. Write a program that checks if all elements in the list [1, True, 3] are True using all().

25
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

Tuple
A tuple in Python is an ordered (you can access them by their index), immutable collection of
items. Tuples are like lists, but they cannot be changed (i.e., they are immutable). Tuples are useful
when you want to store a fixed set of values and ensure that they remain constant throughout the
program. Tuples are created by placing values inside parentheses () separated by commas.

Syntax
Empty tuple
empty_tuple = ()

Single member tuple


Tup_1=(1,)

Tuple with integers


numbers = (1, 2, 3, 4)

Tuple with strings


fruits = ("apple", "banana", "cherry")

Mixed data types


mixed_tuple = (1, "hello", 3.14, True)

Nested tuple (tuple inside another tuple)


nested_tuple = ((1, 2), ("a", "b"), (True, False))

Tuple Slicing
# Slicing a tuple
numbers = (1, 2, 3, 4, 5, 6)
print(numbers[1:4]) # Output: (2, 3, 4)
print(numbers[:3]) # Output: (1, 2, 3)
print(numbers[3:]) # Output: (4, 5, 6)
print(numbers[::2]) # Output: (1, 3, 5)

26
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

Concatenation
You can combine tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
also check this
combined_tuple[0] #1-D
combined_tuple[1] #1-D

Repetition
Use the * operator to repeat a tuple multiple time.
numbers = (1, 2, 3)
repeated_tuple = numbers * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

In operator
Check if an element is in a tuple with in and not in.
fruits = ("apple", "banana", "cherry")
print("apple" in fruits) # Output: True
print("orange" not in fruits) # Output: True

Built-in functions
Function Description Example
len(tuple) Returns the number of len((1, 2, 3)) → 3
elements in the tuple.
max(tuple) Returns the maximum max((1, 2, 3)) → 3
element in a tuple (numbers
only).

27
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

min(tuple) Returns the minimum element min((1, 2, 3)) → 1


in a tuple (numbers only).
sum(tuple) Returns the sum of elements sum((1, 2, 3)) → 6
(numbers only).
tuple.count(x) Returns the number of times x (1, 2, 2, 3).count(2) → 2
appears in the tuple.
tuple.index(x) Returns the index of the first (1, 2, 3).index(2) → 1
occurrence of x in the tuple.

Unpacking Tuples
Tuples support unpacking, which lets you assign the elements of a tuple to multiple variables in a
single line.
# Tuple unpacking
point = (1, 2, 3)
x, y, z = point
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3

Tuple in-operator
tup=(1,2,3)
for i in tup:
print(i)
also try these functions
*dir(tup), help()

28
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

Set
In Python, a set is an unordered and mutable collection of unique items. Sets are useful when you
want to store items without duplicates, such as in membership tests or performing set operations
like union, intersection, and difference.

Syntax
Sets are created using curly braces {} or the set() function.

Empty set
empty_set = set()
*Note: To create an empty set, you must use set() instead of {}, as {} creates an empty dictionary.

Set with values


fruits = {"apple", "banana", "cherry"}

Set with mixed data types


mixed_set = {1, "hello", 3.14, True}

Set removes duplicates automatically


numbers = {1, 2, 2, 3, 4, 4}
print(numbers) # Output: {1, 2, 3, 4}

Adding an item
Use add() to add a single item to a set.
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # Output: {'apple', 'banana', 'cherry'}

Removing an item
Use remove() to remove a specific item (raises an error if the item doesn’t exist), or discard() to
remove without error.

29
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

fruits = {"apple", "banana", "cherry"}


fruits.remove("banana")
fruits.discard("orange") # No error if "orange" is not in the set
print(fruits) # Output: {'apple', 'cherry'}

Clearing tuple
Use clear() to empty a set.
fruits.clear()
print(fruits) # Output: set()

Set Operations
Operation Description Example
set.union(other_set) or | Combines all unique {1, 2, 3} | {2, 3, 4}→{1, 2,
elements from both sets. 3, 4}
set.intersection(other_set) or & Returns only elements {1, 2, 3} & {2, 3, 4} → {2,
present in both sets. 3}
set.difference(other_set) or - Returns elements present in {1, 2, 3} - {2, 3} → {1}
the first set but not in the
second.
set.symmetric_difference(other_set) Returns elements in either {1, 2, 3} ^ {2, 3, 4} → {1,
or ^ set but not both. 4}

Other built-in functions


Method Description Example
add(x) Adds element x to the set. my_set.add(4)
update(iterable) Adds all elements from an my_set.update([5, 6])
iterable to the set.
remove(x) Removes x from the set; raises my_set.remove(3)
error if not found.
discard(x) Removes x from the set; no my_set.discard(7)
error if not found.
pop() Removes and returns an my_set.pop()
arbitrary element.
clear() Removes all elements from my_set.clear()
the set.

30
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

set.issubset(other_set) or <= Checks if one set is a subset of {1, 2} <= {1, 2, 3} → True
another.
set1.issuperset(set2) Checks if one set is a superset {1, 2, 3} >= {1, 2} → True
of another.
set1.isdisjoint(set2) Checks if two sets have no {1, 2}.isdisjoint({3, 4}) →
elements in common. True

Set in-operator
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)

Using Sets to Remove Duplicates


One of the common uses of sets is to remove duplicate values from a list:
# Removing duplicates from a list using a set
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}

31
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

Comparison between list, tuple and set


Feature List Tuple Set
Definition Ordered, mutable Ordered, immutable Unordered, mutable
collection collection collection of unique
items
Syntax Square brackets [] Parentheses () Curly braces {} or
set()
Example my_list = [1, 2, 3] my_tuple = (1, 2, 3) my_set = {1, 2, 3}
Mutable Yes, elements can be No, elements cannot Yes, elements can be
changed, added, be changed after added or removed
removed creation
Order Ordered Ordered Unordered
Duplicates Allowed Yes Yes No
Indexing Supported Supported Not supported
Slicing Supported Supported Not supported
Use Cases Collection of ordered Fixed collection of Unique collection of
items, lists allow items that shouldn't items, often for
modification change membership tests
Common Methods append(), extend(), count(), index() add(), remove(),
pop(), remove(), discard(), pop(),
insert() clear()
Set Operations Not supported Not supported Supported: union,
intersection,
difference,
symmetric_difference
Performance Faster access and Generally faster for Faster membership
modification due to fixed data testing due to hash-
indexing based structure

32
LECTURE NOTES, SESSION 2024 by Rimsha Chauhdary

Let’s practice
Task
Tuple
1. Define a tuple with elements of different data types (e.g., integers, strings, floats). Access
the first, middle, and last elements of a tuple using indexing.
2. Create two tuples and concatenate them to form a new tuple.
3. Slice a tuple to get specific portions (first 3 elements, last 3 elements, or every second
element).
4. Use the in keyword to check if a particular element exists within a tuple.
5. Convert a tuple to a list, modify the list (e.g., add or remove an element), and convert it
back to a tuple.
6. Unpack elements from a tuple into individual variables (e.g., a, b, c = (1, 2, 3)).
7. Define a nested tuple (e.g., (1, (2, 3), 4)) and unpack it into individual variables.
8. Create a tuple of integers and sort it by converting it to a list, sorting it, and converting it
back to a tuple.
9. Write a function that takes a tuple as an argument, performs some operation (e.g., summing
the elements), and returns a result.
10. Create a function that returns multiple values as a tuple, such as (max_value, min_value).

Set
1. Create a set with a few elements of different data types (e.g., integers, strings, floats).Use
the .add() method to add a new element to a set. Use the .remove() or .discard() methods
to remove an element from a set.
2. Create two sets and find their intersection using both the & operator and .intersection()
method.
3. Create two sets and check if one is a subset of the other using .issubset() and if one is a
superset of the other using .issuperset().
4. Given a list of elements, convert it into a set to remove duplicates, then convert it back to
a list.
5. Given two lists, use sets to find the elements that are unique to each list.
6. Create a tuple with duplicate values, convert it into a set to remove duplicates, and print
the unique values.
7. Write a function that takes a word as input, converts it to a set, and returns True if it contains
all vowels (a, e, i, o, u) and False otherwise.

33

You might also like