Python inputs using list comprehensions - python-3.x

n = int(input("Enter the size of the list "))
print("\n")
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:n]
print("User list: ", num_list)
can anyone explain this ...... i.e how it will work.THANKYOU

The workflow is once you enter the size of the list value will be stored in variable 'n' and n printed in the interpreter.
n = int(input("Enter the size of the list "))
print("\n")
In the list comprehension input().strip().split() is executed first i.e once you entered data is striped(removed leading and trailing spaces) and split data by space(default behavior) . then you entered data is iterated by iter variable (num) and num was converted into an integer as well as stored in num_list. Then finally you got num_list contains elements as int type.
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())
finally, list slicing as before n elements are returned into num_list.
num_list[:n]
Without list comprehension of how the above code works like......
num_list=[]
n = int(input("Enter the size of the list "))
print("\n")
for num in input("Enter the list items separated by space ").strip().split()):
num_list.append(int(num))
num_list=num_list[:n]
in one short in list comprehension every element in input is iterated by loop and typecasting it into int and before nth index elements are stored into num_list.

Related

What can I do to add a list and sort out all the prime numbers in the list? Python 3

I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.

This is a simple Python question for list

Im trying to take in user input to get a list of numbers and then use a for loop to grab the largest value. For what I have now I can use 8237483294 but It will list each integer as its own independent value and will have its own place in the list so it would be [8,2,3,7,4,8,3,2,9,4] Which was an A+ for what I wanted. But now I want to take it to another place and take multi digit values such as [23,44332,32523,243,22,]
my code is
users_number = input("list number")
numbers = users_number
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
Use string.split().
#Get user input
# (no need for the two variables you used in your example)
numbers = input("List numbers separated by spaces").split()
#Convert to list of ints
numbers = [int(num) for num in numbers]
#Solution 1: use max()
print("Max value:", max(numbers))
#Solution 2: Iterate through list
max_val = numbers[0]
for num in numbers:
if num > max_val:
max_val = num
print(max_val)
On an additional note, I presented 2 possible methods for finding the max value. max() is a built-in that finds the maximum value in the list. There is also the iterating method, which is what you do in your code.
Here is a more user-friendly approach that asks for the numbers one by one from the user. The advantage is that you don't have to rely on your users to enter the correct syntax for a list.
numbers = []
while True:
number = input("Enter a number from your list. When finished with list, enter 'done': ")
if number == "done":
break
else:
numbers.append(int(number))
max_num = max(numbers)
print(max_num)
Simple and elegant one liner:
max(map(int, input("Enter a list: ").split()))

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

How to add a float number into a list until the lenght of the list equals N number?

I have to create a program where it asks for the length of a list of float numbers, then it should ask for the float numbers in the list and finally it will print the average of those numbers. Working with Python 3.
I have tried with list.extend and adding the number with an assignment into the list and adding a float input.
numbersInTheList=int(input())
thoseNumbers=[]
while len(thoseNumbers)!=numbersInTheList:
thoseNumbers=thoseNumbers + float(input())
print(sum(thoseNumbers)/numbersInTheList)
I expect the output to be the average of the numbers in the list.
list.extend is used to extend one list with another. In this case, you want to append a single value to an existing list.
numbersInTheList= int(input())
thoseNumbers = []
while len(thoseNumbers) != numbersInTheList:
thoseNumbers.append(float(input()))
print(sum(thoseNumbers)/numbersInTheList)

How can I make my program recognize if item is a string or an intiger?

I'm doing some python challenges for fun and I've found a challenge which tells me to make a program that takes an input and prints the numbers in the message.
but when I run the program it prints nothing but [] in the same number as the letters in the message, and also it do not recognize if a letter is actually a number or not, it just see every letter as a string and prints empty squares.
Here's the code:
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence:
if item == str():
WORDS.append(item)
if item == int():
NUMBERS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
Have any ideas?
Here is probably what you meant. You have to split the sentence first.
All of the resulting items will be of type string, therefore isinstance will not help.
str.isdigit() checks if a string contains only digits. If it is a number, you can convert it to an integer using int.
WORDS = []
NUMBERS = []
Sentence = input()
for item in Sentence.split():
if item.isdigit():
NUMBERS.append(int(item))
else:
WORDS.append(item)
print(('[%s]' % ', '.join(map(str, NUMBERS))))
If you do not do the split first, it will work too, but give you just single characters in the WORDS list and single numbers in the NUMBERS list.
Typechecking is usually done using isinstance(obj, cls) :
x = 42
print(isinstance(x, int))
print(isinstance(x, str))
but in your case this will not work since input() always returns a string (a string composed of numeric characters is still a string), so the proper solution is to check if the string is composed only of numeric characters (and eventually build an int from it if you need proper ints).
Also, input() returns a single string, and from your namings (WORDS) I assume you want to iterate on the distinct words, not on each characters like you actually do:
words = []
numbers = []
sentence = input()
for item in sentence.strip().split():
if item.isnumeric():
numbers.append(int(item))
else:
words.append(item)
print(('[%s]' % ', '.join(map(str, numbers))))
Use the built-in isinstance function:
if isinstance(item, str):
WORDS.append(item)
if isinstance(item, int):
NUMBERS.append(item)

Resources