Can I read multiline input() during list comprehension? - list-comprehension

This is just for my own curiosity about the language.
I have this working code:
for i in range(n):
name, grade = input(), int(input())
students += [[name, grade]]
Usually with a for loop that's constructing a list, I'm able to write a list comprehension, so I'm curious whether I can in this case.
I've tried a couple of experiments already, both were unsuccessful.
students = [[[name, grade]] for name in input() for grade in input() for i in range(n)]
but I get EOFerror. So maybe it is possible and there's some other error in my code, or maybe it's not at that error is caused by whatever strangeness occurs when I try this.
I also tried:
students = [[[name, grade]] for name, grade in zip(input(), int(input())) for i in range(n)]
Which raises an error informing me the second argument of zip must be iterable.

Yes, you can,
students=[[input(), input()] for i in range(3)]

Related

Sum of two numbers Python

This is my code, but the Spyder keeps saying there is an indexError of list index out of range for a = int(tokens[0]). Please advise.
import sys
input_ = sys.stdin.read()
tokens = input_.split()
a = int(tokens[0])
b = int(tokens[1])
print(a+b)
The below also works, but I see someone running the above code in Linux and worked, and I am on windows, wondering what is the cause of the above not running properly. Thanks all!
def sum_of_two_digits(first_digit, second_digit):
return first_digit + second_digit
if __name__ == '__main__':
a, b = map(int, input().split())
print(sum_of_two_digits(a, b))
To prove you're getting the input you expect, you can print(len(tokens)) or simply print(input_). But suffice to say this is not a Linux/Windows issue. Rather, your tokens variable is empty by the time you index into it (tokens[0]).
You're not getting anything into the input_ value. This may be because you're using read() and are inputing the values in an unexpected way (I am guessing?). input() will probably serve you better - note that the 'Linux' version you refer to uses input(). read() will block until you send an escape sequence, though that probably has happened if you get to the list index error.

List cant store the input append attribute error

I don't know why I'm getting this error. The list has a function called append which adds the data to the list. But my code gives an error: int object has no attribute append. My codes input was
1
5
.....
.*...
.....
.....
I cant able to store the input in nested lists.Its shows an runtime error.Help me solve this.
t=int(input())
l=[]
for i in range(t):
n=int(input())
for x in range(n):
l.appen(list(input()))
I expected that the input will be stored as a nested list,but it throws an error int object has no attribute append.
If you are writing in Python's IDLE, this is a common mistake that happens with me. '1' looks almost same as 'l', so make sure.
t=int(input())
l=[]
for i in range(t):
n=int(input())
for x in range(n):
l.append(list(input())) # 'appen' is not a list attribute, 'append' is.
You can comment on this answer for more queries on this topic. I'll be eager to answer them
I hope it helped.

Entering a word and then searching through and array of words to find the word

I am trying to create a program which checks to see if words entered (when run) are in an array. I would like to use a loop for this.
I have created a list of words and tried a for loop however the code is proving to be erroneous.
def Mylist():
Mylist= [Toyota,BMW,Pontiac,Cadillac,Ford,Opel]
Search=input("Enter a word")
Mylist[1]="Toyota"
for loop in range (1,6):
if Mylist[loop]==Search:
print("found")
break
I have repeated line 4 for the other car manufacturers.
TypeError: 'function' object does not support item assignment
First, here some recommendations to start:
Indentation in Python is IMPORTANT, be careful to have the right indentation. You must take special care when posting code here in SO so your code does not look like complete gibberish.
You should read Naming conventions. TL;DR we use snake_case for naming functions and variables.
If you are not using an IDE (such as PyCharm) to program, or something intelligent that shows the information on functions, you should always check out the documentation (it is beautiful).
Check out the difference between "Toyota" and Toyota. The first one has quotes, it is a string (i.e. chain of characters), it is a primitive type such as integer and boolean; the second is a token that is to be evaluated, it has to be defined before, such as variables, functions and classes.
Search in the docs if there is an in-built function that already does the job you want.
Check out return values in functions. Functions evaluate to None when you do not explicit a return value.
Now to your question. As some people pointed out, there is the in keyword that does exactly what you want.
CAR_BRANDS= ["Toyota", "BMW", "Pontiac", "Cadillac", "Ford","Opel"]
def check_car():
word = input("Enter a word: ")
if word in CAR_BRANDS:
print("found")
return True
print("not found")
return False
If you don't care about the print you can just do return word in CAR_BRANDS
If you actually want to challenge yourself to write the logic, you were right in choosing a for-loop to iterate over the list.
Index in Python starts from 0, and that range does not give you all the indexes to iterate over your list, you are missing the 0 index. Also, we don't like magic numbers, instead of hard-coding the length of your list of car brands, better compute the length!
for i in range(len(CAR_BRANDS)):
if CAR_BRANDS[i] == word:
print("found")
But even better you can directly iterate over the items in your list, no need to do the range, which will give you something like:
CAR_BRANDS= ["Toyota", "BMW", "Pontiac", "Cadillac", "Ford","Opel"]
def check_car():
word = input("Enter a word: ")
for brand in CAR_BRANDS:
if brand == word:
print("found")
return True
print("not found")
return False
If you have any more questions, do not hesitate! Happy coding.

Printing a list method return None

I am an extremely begginer learning python to tackle some biology problems, and I came across lists and its various methods. Basically, when I am running print to my variable I get None as return.
Example, trying to print a sorted list assigned to a variable
list1=[1,3,4,2]
sorted=list1.sort()
print(sorted)
I receive None as return. Shouldn't this provide me with [1,2,3,4]
However, when printing the original list variable (list1), it gives me the sorted list fine.
Because the sort() method will always return None. What you should do is:
list1=[1,3,4,2]
list1.sort()
print(list1)
Or
list1=[1,3,4,2]
list2 = sorted(list1)
print(list2)
You can sort lists in two ways. Using list.sort() and this will sort list, or new_list = sorted(list) and this will return a sorted list new_list and list will not be modified.
So, you can do this:
list1=[1,3,4,2]
sorted=sorted(list1)
print(sorted)
Or you can so this:
list1=[1,3,4,2]
list1.sort()
print(list1)

Indexes and ranges in python

I have this code:
def main():
if (len(sys.argv) > 2) :
P=list()
f= open('Trace.txt' , 'w+')
Seed = int(sys.argv[1])
for i in range(2, len(sys.argv)):
P[i-2] = int(sys.argv[i])
for j in range(0, len(sys.argv)-1) :
Probability=P[j]
for Iteration in (K*j, K*(j+1)):
Instruction= generateInstruction(Seed, Probability)
f.write(Instruction)
f.close()
else:
print('Params Error')
if __name__ == "__main__":
main()
The idea is that I am passing some parameters through the command line. the first is seed and the rest I want to have them in a list that I am parsing later and doing treatments according to that parameter.
I keep receiving this error:
P[i-2] = int(sys.argv[i])
IndexError: list assignment index out of range
what am I doing wrong
PS: K, generateSegment() are defined in a previous part of the code.
The error you see is related to a list being indexed with an invalid index.
Specifically, the problem is that P is an empty list at the time is being called in that line so P[0] is indeed not accessible. Perhaps what you want is to actually add the element to the list, this can be achieved, for example, by replacing:
P[i-2] = int(sys.argv[i])
with:
P.append(int(sys.argv[i]))
Note also that argument parsing is typically achieved way more efficiently in Python by using the standard module argparse, rather than parsing sys.argv manually.
It looks like you might be referencing a list item that does not exist.
I haven't used Python in quite a while but I'm pretty sure that if you want to add a value to the end of a list you can use someList.append(foo)
The problem is that you are assigning a value to an index which does not yet exist.
You need to replace
P[i-2] = int(sys.argv[I])
with
P.append(int(sys.argv[i]))
Furthermore, len(sys.argv) will return the number of items in sys.argv however indexing starts at 0 so you need to change:
for i in range(2, len(sys.argv)):
with
for i in range(2, len(sys.argv)-1):
As you will run into a list index out of range error otherwise

Resources