Turning Input into a list [duplicate] - python

This question already has answers here:
Python- Turning user input into a list
(3 answers)
Create a tuple from an input in Python
(5 answers)
Closed 10 months ago.
Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
values = input("Input some comma separated numbers : ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)
This does work but is there any other easier way?

If you're looking for a more efficient way to do this, check out this question:
Most efficient way to split strings in Python
If you're looking for a clearer or more concise way, this is actually quite simple. I would avoid using "tuple" and "list" as variable names however, it is bad practice to name variables as their type.

Well, the code that you have written is pretty concise but you could remove few more line by using the below code:
values = input("Enter some numbers:\n").split(",")
print(values) #This is the list
print(tuple(values)) #This is the tuple

Related

remove the [''] when printing a list in python [duplicate]

This question already has answers here:
Print list without brackets in a single row
(14 answers)
Closed 5 months ago.
For some reason when I print a list like
list = []
list.append("0")
list.append("1")
print(list[0])
the output will be ["0"]
My actual code is a large block of text. Here's a link to the actual code: https://pastebin.com/Z54NfivR
Try this:
print(*list)
This essentially unpacks your list and its elements are treated as if they were separated by commas in the print function.
I used the name list because that was included in your example but it is a good practice to avoid using python commands as variable names.

I want to read an external file with numbers and copy them into a list. Python [duplicate]

This question already has answers here:
How to sort python list of strings of numbers
(4 answers)
Closed 1 year ago.
from io import open
files=open("file.txt","r")
list=files.readlines()
The file I have put contains numbers and I want to sort those numbers but it does not let
me because it takes it as a list of strings some idea or simple solution to solve this??
One way you can proceed ahead from here onwards is that you iterate over each list of strings you got after list=files.readlines() [please use a different name for your list as it currently coincides with the keyword list], is that you create separate empty list(s) l1 (,l2, l3, etc.) and iterate over your list and covert each string number into a integer number, like:
for i in list:
```l1.append(int(i))```
l1 will have all of the numbers now, in integer format.
just cast the read list of strings to numbers because files reads in python read as a string by default and you can always cast the string value to the needed typee
from io import open
file=open("file.txt","r")
list = []
for line in file.readlines():
for item in line.split(' '):
list.append(int(item))

Trying to use multiple arguments for .append, anyway how? [duplicate]

This question already has answers here:
Which is the preferred way to concatenate a string in Python? [duplicate]
(12 answers)
Closed 4 years ago.
I am trying to append a set of objects combined into one as a single object on the end of a list. Is there any way I could achieve this?
I've tried using multiple arguments for .append and tried searching for other functions but I haven't found any so far.
yourCards = []
cards =["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"]
suits = ["Hearts","Diamonds","Clubs","Spades"]
yourCards.append(cards[random.randint(0,12)],"of",suits[random.randint(0,3)])
I expected the list to have a new element simply as "Two of Hearts" etc. but instead I recieve this error:
TypeError: append() takes exactly one argument (3 given)
You are sending append() multiple arguments not a string. Format the argument as a string as such. Also, random.choice() is a better approach than random.randint() here as stated by: #JaSON below.
3.6+ using f-strings
yourCards.append(f"{random.choice(cards)} of {random.choice(suites)}")
Using .format()
yourCards.append("{} of {}".format(random.choice(cards), random.choice(suites)))
string concatenation
yourCards.append(str(random.choice(cards)) + " of " + str(random.choice(suites)))
#You likely don't need the str() but it's just a precaution
Improving on Alex's join() approch
' of '.join([random.choice(cards), random.choice(suites)])
yourCards.append(' '.join([random.choice(cards), "of", random.choice(suits)]))

Sorting a list of students [duplicate]

This question already has answers here:
Python Sort() method [duplicate]
(3 answers)
Closed 6 years ago.
Hi I am new to programming and I am trying to write a program that takes a list of student names and sorts them to create a class roll. The list of names will be given on a one line separated by a single space. It is in alphabetical order
This is what I want the output to looks like.
This is my current code below and I am not sure why it keeps coming up with errors.
names = input('Students: ')
print('Class Roll')
output = names.sort()
print(output)
You never split the input apart so there isn't anything to sort
names = names.split()
names.sort()
Here are a few problems I see with your code
The input is read as a trying, you need to split this into individual names
sort works inplace, it returns None
You can do the following
Modify the input command as names = input('Students: ').split(' ')
print(names) instead of output
EDIT
To print them in the manner shown in the question do
for name in names:
print(name)

Python: Convert nDimensions list to string and vice versa [duplicate]

This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 7 years ago.
My question is probably simple but I don't be able to figure it out.
Consider this code where mylist can have any number of dimension:
mylist = [[1,2,3,4],[5,6,7]]
mylist
[[1,2,3,4],[5,6,7]]
It's easy to cconvert it to string:
myString = str(myList)
myString
>'[[1,2,3,4],[5,6,7]]'
But how to easily convert it back to the same list ?
I never get it work in any situation using .join or .split.
I want it work in any case of the list was configured.
thanks
Now mylist is a string. (from your code[enter link description here][1])
So now we pass mylist to eval.
Code Example below :
mylist=eval('[[2,3,4,5,6,2],[2,3,4,5,6,2]]')

Categories