num = [1, 2, 3, 4].
Suppose I have a list named 'num'.
I want to print the list this way: 1, 2, 3, and 4.
How do I add 'and' at the end like that?
I'd suggest you to use python's enumerate() function. You can read more about it here: https://docs.python.org/3/library/functions.html#enumerate
This allows us to iterate through the list, but simultaneously keeping track of the index. This is useful because, when the index shows that we are at the last element of the list, which means our index is at len(num)-1, we should output an "and" in front of it (and a full stop . behind it, which is what is shown in your example.
You could do something like this:
for index, x in enumerate(num):
if index != len(num)-1: #not the last number
print("{}, ".format(x), end = "");
else: #the last number
print("and {}.".format(x), end = "");
This yields the output:
1, 2, 3, and 4.
The normal way in Python to insert delimiters like a comma into a list of strings is to use join():
>>> ", ".join(str(x) for x in num)
'1, 2, 3, 4'
but you want and after the last comma:
>>> prefix, _, suffix = ", ".join(str(x) for x in num).rpartition(" ")
>>> print (prefix,"and",suffix)
1, 2, 3, and 4
I know there are similar posts to this topic, however they often focus on the list items being letters and so the outcome often means they are wrapped in double quotes.
However, I am dealing with lists of numbers and I have been unable to find a solution that addresses my need for converting a string representation of a list of numerical lists ...
"[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
... into an actual list of numerical lists, as I mentioned I am dealing with numerical items for math.
list_string = "[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
ini_list = "[" + list_string + "]"
goal = list(ini_list)
print(goal)
#Desired Outcome:
#goal = [[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]]
You can use exec() function, that executes python code.
>>> exec("a = [[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]]")
>>> a
[[1, 2, 3, 4, 5, 6], [5, 1, 4, 6, 3, 2], [3, 6, 4, 1, 5, 2]]
If you take list(string) you will just split string into chars. For example list('[1, 2]') = ['[', '1', ',', ' ', '2', ']'].
But what you have is a string containing a python literal (a piece of code that describes a value). And you need to turn it into actual value. For that there is eval function. So just do goal = eval(ini_list). Hope I helped you.
A very simple (and safe/robust) approach is to use the ast.literal_evel function.
In this case, the ast.literal_eval function is a safe way to evaluate strings and convert them to their intended type, as there is logic in the function to help remove the risk of evaluating malicious code.
Use:
import ast
list_string = "[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
result = ast.literal_eval(f'[{list_string}]')
Output:
[[1, 2, 3, 4, 5, 6], [5, 1, 4, 6, 3, 2], [3, 6, 4, 1, 5, 2]]
Here is one faster way to do so using list comprehension and split():
list_string = "[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
goal = [[int(num) for num in sublist.split(",")] for sublist in list_string[1:-1].split("],[")]
print(goal) # [[1, 2, 3, 4, 5, 6], [5, 1, 4, 6, 3, 2], [3, 6, 4, 1, 5, 2]]
We separate the string at each ],[, to retrieve the different sublists.
Then, we separate each sublist at , and finally convert the separated numbers to integers.
The alternative with for loops would be:
goal = []
for sublist in list_string[1:-1].split("],["):
new_sublist = []
for num in sublist.split(","):
new_sublist.append(int(num))
goal.append(new_sublist)
print(goal)
so I have a list of numbers, and I want to start at the last element of the list and print every other element.
So given list = [1, 2, 3, 4, 5, 6] I would print 6, 4 and 2. My issue is that slicing is not printing the last element.
list = [1, 2, 3, 4, 5, 6]
for i in list[-1::-2]:
print(list[i])
this merely prints 4 and 2, showing me that the last digit is not included. I have also tried omitting the -1 and just using list[::-2]. It takes every odd digit (4 and 2) but does not include 6. I want to use slicing to achieve this result, but clearly I am misunderstanding how to use it. Any help much appreciated (this is my first stackOverflow question btw!)
Please avoid using the variable names as a list.
ls = [1, 2, 3, 4, 5, 6]
for i in ls[-1::-2]:
print(i)
You're iterating all the elements of the list using the in method. It doesn't provide you an index that you will use to print.
When you're trying to print list[i] it will raise an error because when i=6 then list[i] element don't exist in the list.
You can simply do slicing by using:
ls = [1, 2, 3, 4, 5, 6]
print(ls[-1::-2])
and don't use the list as a variable name because it is a keyword in Python so you will get an error.
Have you tried printing just i instead of the list[i]?
You should remember here that if you iterate through a reversed list, you need not do indexing again. The i would hold the value of the list element.
Please try:
for i in ls[::-2]:
print(i)
I want to add numbers to a pre-existing list and preserve no spacing between comma separated values but when I use the extend function in python, it adds spaces.
Input:
x=[2,3,4]
y=[5,6,7]
Run:
x.extend(y)
Output:
[2, 3, 4, 5, 6, 7]
Desired output:
[2,3,4,5,6,7]
If you don't need to keep its type when printing, You can convert the type of variables with str() and replace whitespaces to ''.
x=[2,3,4]
y=[5,6,7]
x.extend(y)
x_removed_whitespaces = str(x).replace(' ', '')
print(x_removed_whitespaces)
output:
[2,3,4,5,6,7]
In Python, lists are printed in that specific way.
>>> x = [2,3,4]
>>> print(x)
>>> [2, 3, 4]
If you want the print function to print the lists in some other way, then you would have to change/override the print method manually, and then specify how you want to print the list. It is explained here.
You could write your own function that prints the list the way you want:
def printList(aList):
print('['+",".join(map(str,aList))+']')
x=[2,3,4]
y=[5,6,7]
x.extend(y)
printList(x)
Output:
[2,3,4,5,6,7]
I have this list:
somestuff = [1,2,3,"4n5"]
I want to split the last index with the letter n. I am expecting this result:
>>>[1,2,3,4,5]
But when I use the .split() method on the last element of the list, like shown:
somestuff[-1] = somestuff[-1].split("n")
print(somestuff)
I get this result:
>>>[1,2,3,[4,5]]
How do I split the last index of a list and get my expectation? Is there any other way to do it?
Using a range-replacement gives a succinct piece of code:
somestuff[-1:] = somestuff[-1].split('n')
The trick is telling python that you want to replace a range of elements with a different range of elements. The question's example replaces a single element with a range.
another possible solution:
somestuff = [1,2,3,'4n5']
somestuff = somestuff + [int(x) for x in somestuff.pop().split('n')]
output:
[1, 2, 3, 4, 5]
Can it meet your need?
newstuff = somestuff[:-1] + list(map(lambda x: int(x), somestuff[-1].split("n")))
newstuff # [1, 2, 3, 4, 5]