tuple unpacking in python using for loops? - python-3.x

l=[(1,2),(3,4),(5,6)]
for (a,b) in list:
for i in range(len(list)):
if i%2==0:
print(b)
break
else:
print(a)
break
output-
2
4
6
expected output-
1
4
5
PLEASE correct it!

You may want to be more specific about what you want to achieve.
Based on your "expected output", I assume you want the 1st element when the index is even and the 2nd element when the index is odd.
l=[(1,2),(3,4),(5,6)]
for idx, (x, y) in enumerate(l):
val = x if idx%2==0 else y
print(val)

Related

For loop passes list with step: 2, but i didn`t want it

a = [1,2,3,4,5]
for i in a:
print(i) # returns 1,3,5
if i < 5:
a.remove(i)
print(a) # returns [2,4,5]
Just for example. This code is used in codewars solution.
a = [1,2,3,4,5]
for i in a:
print(i) # returns 1,3,5
if i < 5:
a.remove(i)
print(a) # returns [2,4,5]
The issue here is for loop is going through index.
Iteration 1:a=[1,2,3,4,5]
index =0
i=1
while you are doing a.remove will remove 1 and list will have [2,3,4,5]
Iteration 2:a=[2,3,4,5]
index=1
i=3
2 will be skipped as it is in index 0 now.
which is giving the result such a way
If you change your for loop iterator, it will work as expected. So for i in range(1, 5) (or for i in range(1, len(a)) if you need to reference a) instead of for i in a - it's because you are changing the list while iterating through it.

range function with if-else statment in python

when I enter
45 200
why I am getting no
and the reason is the if-else statement is coming false
but I don't know why
T = int(input("i"))
for _ in range(T):
X,Y = map (int, input().split(" "))
if Y in (X, X+200):
print("yes")
else:
print("no")
if Y in (X,X+200) will check if Y exists in the tuple consisting of the values X and X+200. You might be looking for the python range function.
if Y in range(X,X+200) should do what you need.

Sum function not working when trying to add numbers in lists using python

I am trying to create a program that takes only even numbers from a range of numbers from 1 to 100 and add all of the even numbers. I am a beginner and I have been trying to get this working since yesterday, and nothing I have tried works. This is my first post, so sorry if the format is wrong but here is my code.
for i in range(1, 100):
if i % 2 == 0:
x = [I]
y = sum(x)
print(y)
The problems with your code has multiple issues that - 1)if you want to get all even numbers from 1 to 100, your range should be (1, 101); 2) the way you build list is wrong (syntax); 3) the sum expect an iterable (list).
There are a few ways to accomplish this sum from 1 to 100 (inclusive), here it will start with yours, and try to show List Comprenshion and Generator Expression way:
lst = [] # to store the build-up list
tot = 0 # to store the answer
for i in range(1, 101):
if i % 2 == 0: # it's a even number
lst.append(i) # store it into lst
tot = sum(lst) # 2550
Generator expression:
all_evens_sum = sum(x for x in range(1, 101) if x % 2 == 0) # 2550
Or List Comprehension:
lst = [x for x in range(1, 101) if x % 2 == 0] # even nums
total = sum(lst) # 2550
I am a beginner too but it looks I can help you some.
for i in range(1, 100):
if(i % 2 == 0):
sum += i
print(sum) // do what you want

Making a matrix in python 3 without numpy using inputs

I want to have two inputs : a,b or x,y whatever...
When the user inputs say,
3 5
Then the shell should print a matrix with 3 rows and 5 columns also it should fill the matrix with natural numbers( number sequence starting with 1 and not 0).
Example::
IN :2 2
OUT:[1,2]
[3,4]
If your objective is only to get the output in that format
n,m=map(int,input().split())
count=0
for _ in range(0,n):
list=[]
while len(list) > 0 : list.pop()
for i in range(count,count+m):
list.append(i)
count+=1
print(list)
I am going to give a try without using numpy library.
row= int(input("Enter number of rows"))
col= int(input("Enter number of columns"))
count= 1
final_matrix= []
for i in range(row):
sub_matrix= []
for j in range(col):
sub_matrix.append(count)
count += 1
final_matrix.append(sub_matrix)
Numpy library provides reshape() function that does exactly what you're looking for.
from numpy import * #import numpy, you can install it with pip
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = range(1, n*m+1) #You want the range to start from 1, so you pass that as first argument.
x = reshape(x,(n,m)) #call reshape function from numpy
print(x) #finally show it on screen
EDIT
If you don't want to use numpy as you pointed out in the comments, here's another way to solve the problem without any libraries.
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = 1 #You want the range to start from 1
list_of_lists = [] #create a lists to store your columns
for row in range(n):
inner_list = [] #create the column
for col in range(m):
inner_list.append(x) #add the x element and increase its value
x=x+1
list_of_lists.append(inner_list) #add it
for internalList in list_of_lists: #this is just formatting.
print(str(internalList)+"\n")

Modify all integers in 2d list and make them even

When I run this through the visualizer it only modifies the first element in the 2d list. How do I make it so that the it runs throught the entire list.
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss)):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
xss = [[1,2,3],[],[4,5]]
make_even(xss)
print(xss)
So first off you need to correct your indentation in your code:
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss)):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
However, because both your loops use len(xss), they expect an array of 3 lists each with 3 elements. If you'd want each list to have variable numbers of elements you should do this instead:
def make_even(xss):
for i in range(len(xss)):
for j in range(len(xss[i])):
if xss[i][j] % 2!= 0:
xss[i][j] += 3
return xss
Which returns: [[4, 2, 6], [], [4, 8]]
However, there are two obvious changes I would make:
Your if statement should be if xss[i][j] % 2 == 1, since it's more readable.
You can make a number even by adding 1. (If 3 is required for your specs that's fine).
Also, this is totally doable in a single line (any line would work):
# List comprehensions only
xss = [[(x + 3 if x % 2 == 1 else x) for x in row] for row in xss]
# map and lamdbas (returns lists)
xss = list(map(lambda row: list(map((lambda x: x + 3 if x % 2 == 1 else x),row)), xss))
# map and lamdbas (returns iterables)
xss = map(lambda row: map((lambda x: x + 3 if x % 2 == 1 else x),row), xss)
Although personally, I think the list comprehensions is the easiest to read.

Resources