0% found this document useful (0 votes)
4 views15 pages

Hints AI Session 2.ipynb - Colab

The document provides a comprehensive overview of list and tuple functions in Python, including methods for modification, searching, counting, sorting, and copying. It also covers conditional statements, loops, and input handling, demonstrating various examples and use cases. Additionally, it explains the difference between shallow and deep copies in lists.

Uploaded by

medo1234432144
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)
4 views15 pages

Hints AI Session 2.ipynb - Colab

The document provides a comprehensive overview of list and tuple functions in Python, including methods for modification, searching, counting, sorting, and copying. It also covers conditional statements, loops, and input handling, demonstrating various examples and use cases. Additionally, it explains the difference between shallow and deep copies in lists.

Uploaded by

medo1234432144
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/ 15

keyboard_arrow_down List Functions

Modification Methods

append(x) – Adds an element to the end of the list.


extend(iterable) – Adds all elements of an iterable to the end of the list.
insert(index, x) – Inserts an element at a specific position.
remove(x) – Removes the first occurrence of an element.
pop(index) – Removes and returns an element at a given index (default is the last element).
clear() – Removes all elements from the list.

Searching & Counting

index(x, start, end) – Returns the index of the first occurrence of an element.
count(x) – Returns the number of times an element appears in the list.

Sorting & Reversing

sort(reverse=False, key=None) – Sorts the list in ascending order (or descending if reverse=True).
reverse() – Reverses the order of elements in the list. Copying & Other Operations
copy() – Returns a shallow copy of the list.
len(list) – Returns the number of elements in the list.
max(list) – Returns the largest element.
min(list) – Returns the smallest element.
sum(list) – Returns the sum of elements (if they are numeric).
sorted(list, reverse=False, key=None) – Returns a new sorted list without modifying the original.
any(iterable) – Returns True if at least one element is truthy.
all(iterable) – Returns True if all elements are truthy.
x = [55, 22, 33, 77, 26]
x.sort() # By default it will sort ascending order.

print(x)

[22, 26, 33, 55, 77]

x = [55, 22, 33, 77, "W"]


x.sort() # By default it will sort ascending order.

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-5ea86c8edc8d> in <cell line: 0>()
1 x = [55, 22, 33, 77, "W"]
----> 2 x.sort() # By default it will sort ascending order.

TypeError: '<' not supported between instances of 'str' and 'int'

x = ["welcome", "Welcome", "hello", "ali", "AI"]


x.sort()
print(x)

['AI', 'Welcome', 'ali', 'hello', 'welcome']

x = [55, 22, 33, 77, 26]


x.sort(reverse = True) # It will sort descending order.
print(x)

[77, 55, 33, 26, 22]

x = [55, 66, 33, 22, 77]


print(x.sort())

None
print(x)

[22, 33, 55, 66, 77]

x.sort()
print(x)

[22, 33, 55, 66, 77]

x = "welcome"
print(x.replace("e", "a"))

walcoma

print(x)

welcome

x = [55, 66, 77]


print(x.pop())

77

print(x.append(68))

None

print(sorted(x))

[55, 66, 68]


x = [55, 66, 77]
print(max(x))

77

print(min(x))

55

print(sum(x))

198

x = [99, 66, 77]


sorted(x)
print(x)

[99, 66, 77]

print(sorted(x, reverse=True))

[99, 77, 66]

x = [5, 6, 7, 8, 9]
y = x
y[3] = 66
print(x)
print(y)

[5, 6, 7, 66, 9]
[5, 6, 7, 66, 9]

x = [5, 6, 7, 8, 9]
y = x[:]
y[3] = 66
print(x)
print(y)

[5, 6, 7, 8, 9]
[5, 6, 7, 66, 9]

# copy ==> Shallow Copy


x = [5, 6, 7, 8, 9]
y = x.copy()
y[3] = 66
print(x)
print(y)

[5, 6, 7, 8, 9]
[5, 6, 7, 66, 9]

x = [5, 6, 7, 8, 9, [5, 6, 7]]


print(x[5][2])

y = x.copy() # Shallow Copy


y[5][2] = 77
x[5][1] = 65
x[0] = 99
print(x)
print(y)

[99, 6, 7, 8, 9, [5, 65, 77]]


[5, 6, 7, 8, 9, [5, 65, 77]]

x = [5, 6, 7, 8, 9, [5, 6, 7]]


y = x[:] # Shallow
y[5][2] = 77
print(x)
print(y)

[5, 6, 7, 8, 9, [5, 6, 77]]


[5, 6, 7, 8, 9, [5, 6, 77]]

1. copy() (Shallow Copy)

Creates a new object but does not recursively copy nested objects.
If the list contains mutable objects (e.g., other lists or dictionaries), they are referenced rather than copied.
Changes to nested objects in the copied list affect the original list.

2. deepcopy() (Deep Copy)

Recursively copies all objects, including nested ones.


Changes to nested objects in the copied list do not affect the original list. Used when a complete independent copy is needed.

# Deep Copy
import copy
x = [5, 6, 7, 8, 9, [5, 6, 7]]
y = copy.deepcopy(x)
x[5][2] = 77
y[3] = 66
y[5][1] = 22
print(x)
print(y)

[5, 6, 7, 8, 9, [5, 6, 77]]


[5, 6, 7, 66, 9, [5, 22, 7]]

x = [5, 6, 7]
x.reverse()
print(x)

[7, 6, 5]
Get the second largest number in list: [5, 77, 66, 20, 35] in one line.

x = [5, 77, 66, 20, 35] # [5, 20,, 35,, 66, 77]
x.sort()
x[-2]

66

sorted(x)[-2]

66

x = [77, -5, 7]
all(x) # And
# any value not 0 this evaluates to True.
x = [] # This evaluates to False.

True

x = [0, 0, 0]
any(x) # Or

False

x = [55, 66, 77, 88, 66, 99]


print(x.index(66, 2, -1))

Lis Comprehension
keyboard_arrow_down Tuples
# Tuples ==> Colletion of elements that can be with diffferent datatypes.
# Tuples are Immutable ==> Can't be Modified.
# Tuples are defined using ()
x = (5, 6, 7, 8, 9, True, "Welcome")
print(x[0])

print(x[-1])

Welcome

print(x[1:5])

(6, 7, 8, 9)

x[::-1]

('Welcome', True, 9, 8, 7, 6, 5)

x = (5, 6, 7, 8, 9, True, "Welcome", "Welcome")


x.count("Welcome")

x.index(True)

x[0] = 55
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-61-4d0c2147cdf2> in <cell line: 0>()
----> 1 x[0] = 55

TypeError: 'tuple' object does not support item assignment

# Use Casting
x = (5, 6, 7, 8, 9, True, "Welcome", "Welcome")
x = list(x)
x[0] = 55
x = tuple(y)
print(x)

(5, 6, 7, 66, 9, [5, 22, 7])

x = (4,) # Tuples with only one value, the value must be followed by a comma.
print(type(x))

<class 'tuple'>

Assigns multiple values to multiple variables in a single line. x is assigned 5, and y is assigned "welcome".

# Multiple Assignment
x, y = 5, "welcome"
(x, y, z) = (5, 6, 7)
x, y, z = (5, 6, "hello")
(x, y, z) = 5, 6, "hello"

print() ==> cout

input()
string name;

cout<<"Enter your name";

cin>>name;

name = input("Enter your name: ")

Enter your name: Mostafa

print(name)

Mostafa

age = int(input("Enter your age: "))


print(age)
print(type(age))

Enter your age: 25


25
<class 'int'>

salary = float(input("Enter your salary: "))


print(salary)
print(type(salary))

Enter your salary: 2500


2500.0
<class 'float'>

Take an input of a list of 5 values in a single input function.

x = input("Enter 5 values ").split() # "55 66 welcome 77 hello".split() ==> [55, 66, welcome, 77, hello]
Enter 5 values 55 66 welcome 77 hello

print(x)

['55', '66', 'welcome', '77', 'hello']

print("Welcome", "AI", end = "_")


print("Hello", end = "_")

Welcome AI_Hello_

print("Welcome", "Hello", sep = "_")


print(5)

Welcome_Hello
5

keyboard_arrow_down Loops and Conditions


if (x%2 == 0)
{
line 1
line2
}

x = 55 # even: Divided by 2 with no reminder. odd: Divided by 2 with reminder.


# Conditions ==> if
"""
if condition:
line1
line2
print("Hello")
"""
if x%2 == 0:
print("even")
print("Hello")
print("Okay")

Okay

x = 55
if x%2 != 0:
print("odd")
print("Hello")
print("Okay")

odd
Hello
Okay

== – Equal to
!= – Not equal to
> – Greater than
< – Less than
>= – Greater than or equal to
<= – Less than or equal to

In python 2: not equal <>

grade = int(input("Enter Your Grade ")) # Numeric Value ==> 75


# and
if grade >= 85 and grade <= 100:
print("Excellent")
elif grade >= 75 and grade < 85:
print("Very Good")
elif grade >= 65 and grade < 75:
print("Good")
elif grade >= 50 and grade < 65:
print("Pass")
else:
print("Fail")

Enter Your Grade 85


Excellent

if 85 <= grade <= 100:


print("Excellent")
elif 75 <= grade < 85:
print("Very Good")
elif 65 <= grade < 75:
print("Good")
elif 50 <= grade < 65:
print("Pass")
else:
print("Fail")

Excellent

x = 55
# or
if x == 55 or x > 100:
print("Hello")

Hello

For Loops
# Loops ==> Iterates over something.
x = [11, 12, 3, 4, 5]
for i in x: # In each iteration i will carry a value in x.
print(i)

11
12
3
4
5

list(range(5)) # range(number): will create an object like list from 0 to number - 1

[0, 1, 2, 3, 4]

list(range(7))

[0, 1, 2, 3, 4, 5, 6]

list(range(2, 7, 2))

[2, 4, 6]

range_of_5 = range(5) # [0, 1, 2, 3, 4]


for i in range_of_5:
print(i)

0
1
2
3
4
x = [11, 12, 3, 4, 5]
len(x) # This will return the number of elements found in x.

5
length_of_list = len(x) # 5
range_of_list = range(length_of_list) # [0, 1, 2, 3, 4]
for i in range_of_list:
print(x[i])

11
12
3
4
5

for i in range(len(x)):
print(x[i])

You might also like