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]
Related
In Python, I'm aware that '\n' adds a new line when using a string inside of a print call. But how do I add a new line when using a variable inside of the print function?
For example:
print("\nHello") # <----- string used, no issues here
produces
>>> print("\nHello")
Hello
Now suppose I have a list named guest_list. How would I do something akin
to "print('\n'guest_list)", printing an empty line and then the list?
Thanks for any help offered!
You can pass an empty string as the first argument and sep='\n' if you want to avoid formatting/concatenation before printing.
>>> guest_list = [1, 2, 3]
>>> print('', guest_list, sep='\n')
[1, 2, 3]
... or equivalently:
>>> print('\n', guest_list, sep='')
[1, 2, 3]
Or convert to string, then add '\n' to it:
>>> l=[1,2,3]
>>> print('\n'+str(l))
[1, 2, 3]
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]
This question is different from others because I am trying to print lists that have round brackets, not the square ones.
For example; I have this list:
list_of_numbers = [1, 2, 3, 4, 5]
When you print out the list, you get this:
[1, 2, 3, 4, 5]
I want the printed version to look something like this:
(1, 2, 3, 4, 5)
print(tuple(list_of_numbers))
or
print('(%s)' % ', '.join([str(i) for i in list_of_numbers]))
list_of_number_strings = [str(number) for number in list_of_numbers]
list_string = "({})".format(", ".join(list_of_number_strings))
print(list_string)
Should do the trick
The list_of_number_strings uses a simple list comprehension create a list of strings by casting every element in list_of_numbers to a string.
Then we use simple string formatting and a join to create the string we want to print.
tuple will print the round brackets
print(tuple(list_of_numbers))
I know we can merge two lists by using something like final_list= list1 + list2 but if the lists are generated by a python code and they don't have a variable associated with them like list1 and list2, how can we merge them? Say, my code does something like print output to give:
[1,2,3,4]
[2,0,5,6]
I'd like to merge them so I can get unique values using set(final_list). But how do I get the final_list?
PS- My code can return multiple lists. It is not restricted to two.
def somefunc(param):
#does something
return alist,blist
my_alist,my_blist = somefunc(myparam)
print my_alist, my_blist
#prints both lists.
When you return multiple values from a function they are returned in a tuple. You can easily unpack the tuple
You can either modify the function which is generating output, or the harder way being you manually convert it into a string and then into a set.
list = []
strings_of_list = output.split('\n')
for string in strings_of_list:
values = string[1:-1].split(',')
for val in values:
list+=[int(val)]
set(list)
Assign a variable to a function. Taking the lists the function generated, join them together in another variable. Just make sure that your function returns the generated list, and doesn't just print it out.
# my_list_generator returns two values.
>>> a, b = my_list_generator()
>>> a
[1, 2, 3, 4]
>>> b
[2, 0, 5, 6]
>>> final_list = a + b
>>> final_list
[1, 2, 3, 4, 2, 0, 5, 6]
Cross all that out! Now that I know the function can return multiple objects, let do this (with a little list comprehension):
lists = [i for i in my_list_generator()]
# lists might look like [[1, 2, 3, 4], [2, 0, 5, 6]]
# And now use a for loop to get each value
final_list = []
for sublist in lists:
final_list.extend(sublist)
# final_list will look like [1,2,3,4,2,0,5,6]
Also, if you don't want duplicates, just do one more thing:
real_final_list = [i for i in final_list if i not in real_final_list]
If I understand correctly:
You have a function (let's call it listGen() for now) which returns some number of lists. Now, you want to put these list together into one big list, final_list.
You could do the following:
# listGen defined earlier
final_list = []
for i in listGen():
final_list += i
unique_values = set(final_list) # or whatever you wanted to do with it
Since listGen returns a tuple, we can loop over its contents, those being the lists you want to append to each other.
Sorry if this is a duplicate question, I searched and couldn't find anything to help.
I'm currently trying to compare two lists. If there are any matching items I will remove them all from one of the lists.
However the results I have are buggy. Here is a rough but accurate representation of the method I'm using:
>>> i = [1,2,3,4,5,6,7,8,9]
>>> a = i
>>> c = a
>>> for b in c:
if b in i:
a.remove(b)
>>> a
[2, 4, 6, 8]
>>> c
[2, 4, 6, 8]
So I realised that the main issue is that as I remove items it shortens the list, so Python then skips over the intermediate item (seriously annoying). As a result I made a third list to act as an intermediate that can be looped over.
What really baffles me is that this list seems to change also even when I haven't directly asked it to!
In python, when you write this:
i = [1,2,3,4,5,6,7,8,9]
You create an Object (in this case, a list) and you assign it to the name i. Your next line, a = i, tells the interpreter that the name a refers to the same Object. If you want them to be separate Object you need to copy the original list. You can do that via the slicing shorthand, i[:], or you can use a = list(i) to be more explicit.
The easiest way to do this is use a set to determine shared items in a and b:
for x in set(a).intersection(b):
a.remove(x)
Your statements a = i and c = a merely make new names that reference the same object. Then as you removed things from a, it's removed from b and i, since they are the same object. You'll want to make copies of the lists instead, like so
a = i[:]
c = a[:]
a = i Doesn't make a copy of a list, it just sets another variable, i to point at your list a. Try something like this:
>>> i = [1, 2, 3, 2, 5, 6]
>>> s = []
>>> for i in t:
if i not in s:
s.append(i)
>>> s
[1, 2, 3, 5, 6]
You can also use set which guarantees no duplicates, but doesn't preserve the order:
list(set(i))