+ 1

How could I append a range number from an input to a list??

A noobie here I was wondering why I couldn't in python append a range int to a list. Here is the code and if someone wouldn't mind in help me I'll be so grateful: li = [] height = input("height: ") short = range(140, 166) for height in short: li.append("short")

16th May 2020, 6:51 PM
Martin
Martin - avatar
7 Réponses
+ 4
if height in list(range(140,166)): when you are a bit more experienced, you can read about lists and generators, generator expressions. For now just remember some ways how to convert a range to a list.
16th May 2020, 7:54 PM
Oma Falk
Oma Falk - avatar
+ 2
it throws TypeError i think. i think you want to append the height to the list short... if so you can do it like this: height = int(input()) short = [x for x in range(140,166)] short.append(height) [x for x in range(140,166)] is a list comprehension and it means this: short = [] for x in range(140,166): short.append(x)
16th May 2020, 6:56 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
+ 2
li = [] height = int(input("height: ")) # <= convert to int. short = range(140, 166) if height in short: # <= use "if" not "for". li.append("short") print(li)
16th May 2020, 7:30 PM
rodwynnejones
rodwynnejones - avatar
+ 2
Thanks you guys for the help i was circling with this for a few days 🙇‍♂️🙇‍♂️
16th May 2020, 7:31 PM
Martin
Martin - avatar
+ 1
Almost something like that :( what i want is append the word "short" when someone type a number (with the input height) between the range(140, 166) i dont know how to do that. li its an empty list to storage different type of words :(
16th May 2020, 7:15 PM
Martin
Martin - avatar
+ 1
for multiple values you can use this height = input().split() and add from keyboard using a space between the values like this: 34 63 83 3 236 after that you need to do the logic like this for i in height: if int(i) in short: result[i] = 'short' else: result[i] = 'tall' it should look like this in its final form: height = input().split() result={} short = [x for x in range(140,166)] for i in height: if int(i) in short: result[i] = 'short' else: result[i] = 'tall' print(result)
16th May 2020, 7:25 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
0
this one uses a dictionary, which stores the input number as key, and the word 'short' as value. i added for 'tall' also. feel free to delete the else and the statement below the else if you want only the short values height = int(input()) result={} short = [x for x in range(140,166)] short.append(height) if height in short: result[height] = 'short' else: result[height] = 'tall' print(result)
16th May 2020, 7:21 PM
Sebastian Pacurar
Sebastian Pacurar - avatar