how to use assignment operator in list comprehension - python

i want to create a list of random integers
I want the value of num to be a random integer The following line of code gives me a syntax error
invalid syntax
i just want to know that is there any way to do this using list comprehension
numbers = [num for num in range(1,6) num = random.randint(1,10)]

Looking at your requirements, you aren't required to assign num.
To generate a list of random numbers simply do:
numbers = [random.randint(1,10) for _ in range(1,6)]
You can alternatively do:
numbers = random.sample(range(1,11),k=5) # k is the repeating count

You don't need the num variable, just use the random.randint() call.
numbers = [random.randint(1,10) for _ in range(1,6)]

Related

List updation statement showing index out of range

List=eval(input('enter list of numbers and string :'))
for x in range(1,len(List)+1,2):
List[x]=List[x]*2
print(List)
i want to update value at odd index but, why i don't know the statement 3 is generating error**List[x]=List[x]2 showing me error -index out of range**
There's three issues with your code:
eval() on user input is risky business. Use ast.literal_eval() instead.
Your for loop has an off-by-one error. Remember that array indices start at zero in Python.
List is not a good variable name, as it conflicts with List from the typing module. Use something like lst instead.
import ast
lst = ast.literal_eval(input('enter list of numbers and string :'))
for x in range(0, len(lst), 2):
lst[x] = lst[x] * 2
print(lst)

How to sort only positive numbers from a list?

I am trying to make a list of only sorted positive list when the user gives positive and negative integers in that list. For example, if the user gave "10 -7 4 39 -6 12 2" my program would only sort the positive numbers and give out '2 4 10 12 39'.
So far this is what my code looks like:
list = input().split()
positive_list = []
for i in range(list):
if list[i] > 0:
positive_list.append(list[i])
i+=1
positive_list.sort()
print(positive_list)
You have several issues:
you have a variable that's named the same as a basic type (list), which shadows the type; pick a better name
for i in range(my_list): doesn't do what you think; you could do for i in range(len(my_list)):, but you can also just for n in my_list: and n will be every element in my_list in turn
your user enters text, you'll need to turn those strings into integers before comparing them to other integers, using int()
you do for i .. but also i += 1 you don't need to increment the for-loop variable yourself.
Look into list comprehensions, they are perfect for what you're trying to do in a more complicated way, to construct positive_list.
Your solution could be as simple as:
print(sorted([int(x) for x in input().split() if int(x) > 0]))
But staying closer to what you were trying:
numbers = [int(x) for x in input().split()]
sorted_positive_numbers = sorted([x for x in numbers if x > 0])
print(sorted_positive_numbers)
If you insist on a for-loop instead of a list comprehension:
numbers = [int(x) for x in input().split()]
positive_numbers = []
for number in numbers:
if number > 0:
positive_numbers.append(number)
print(sorted(positive_numbers))
Rename list to something other than that. list is a python keyword.
For example list_new or list_temp
My suggestion is to try it like this:
positive_list = []
for num in listNew:
if num > 0:
positive_list.append(num)
positive_list.sort()

Removing duplicates and sorting list python

Given a list, I need to print the numbers in sorted order and remove any duplicates. I am using python 3.7.2
My code:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = input().split()
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
However, whenever my input consists of a 2 digit number, the logic fails.
Eg. for input of 2 1 43 2 5, I get an output of 1 2 43 5.
This work perfectly for single digit numbers. Can someone help me out with this?
You only need a slight modification. You are comparing strings instead of numbers, so try this instead:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = map(int, input().split())
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
If you want, you can also do:
numbers = (int(x) for x in input().split())
You can simplify this in various aspects. Sort by numeric value using an appropriate key function, use a for loop if you know the number of iterations beforehand, utilize appropriate string utils like str.join, etc.
testcases = int(input())
for _ in range(testcases):
print(' '.join(sorted(set(input().split()), key=int)))
You are going correct way with set(numbers) to remove duplicates. The problem comes from sorted with your numbers being list of strs not ints.
Try this:
x_numbers = input().split()
numbers = [int(x) for x in x_numbers]
Try it now:
testcase = int(input())
n=list(str(testcase))
results = map(int, n)
numbers= sorted(set(results))
print(numbers)
code here:https://repl.it/repls/SeriousRosybrownApplicationprogrammer
We can keep it simple like this. This is a reference
input=raw_input() #took input as string
inputlist=input.split() #split the string to list
lsintegers = map(int, list(set(inputlist))) #remove duplicates converted each element to integer
lsintegers.sort() #sorted
print(lsintegers)`

Python Error. Trying to convert number into list and pull out first digit

So this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
Is giving me the TypeError: 'int' object has no attribute 'getitem'.
But if I change the 3rd line from n into i then this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(i[0])
list = lst
print list
print first_n
Gives me the list and the last number on that list. I need the first number not the last.
It gives me the first if instead I replace n in range (500): with n = raw input()
n = raw_input()
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
But this is single number and need to have run thousands of numbers. (As you can see I change the i on the 3rd line back into n)
Please can you help?
Your issue lies with the raw_input. In python 2, it returns a string, not an integer. What you need is input(), which just returns an integer:
n = input()
lst = [int(i) for i in str(n)]
first_n = int(lst[0]) #also, need lst here, not n, as it is now an integer
list = lst
print list
print first_n
Probably an easier solution here is to instead convert it to a string:
>>> str(123)[0] # Convert to string and take 1st character
'1'
If you need it as a number, you can int it back. This feels inefficient, but you're trying to solve a problem strongly related to the written representation of a number, so strings feel like the appropriate solution. You can however use solutions related to taking the place value. If you are looking for the number of hundreds in the above, for example, you could % 100. This requires a little more work to make general, though.

will my 6 digit number code work?

i need to generate all 6 digit number for a word list
will this code work?
from random import randint
list = [111111]
print ('111111')
while True:
number = randint(100000,999999)
if not number in list:
list.extend(str(number))
print(number)
Instead of randomly trying out numbers and then adding them one character at a time (look into append() rather than extend()), simply send the range() object to list():
numbers = list(range(100000, 1000000))
Note that I've called it numbers rather than list, to avoid masking list().
If you want each number as a string, map them to strings:
numbers = list(map(str, range(100000, 1000000)))
Your method would work but would be very slow. I would suggest using list comprehension to generate the list of numbers. If you need it to be randomized, there is a shuffle method as part of the random module.
from random import shuffle
#if you wanted just numbers
x_all_numbers = [i for i in range(100000, 999999)]
#if you wanted strings of different numbers
x_str_numbers = [str(i) for i in range(100000, 999999)]
print(x_all_numbers[0:10])
shuffle(x_all_numbers)
print(x_all_numbers[0:10])
To show that this will work, I included the output:
[100000, 100001, 100002, 100003, 100004, 100005, 100006, 100007, 100008, 100009]
[783780, 170070, 270425, 119709, 194098, 617834, 740368, 420370, 993130, 712673]

Categories