Print a list of space-separated elements - python

I have a list L of elements, say natural numbers. I want to print them in one line with a single space as a separator. But I don't want a space after the last element of the list (or before the first).
In Python 2, this can easily be done with the following code. The implementation of the print statement (mysteriously, I must confess) avoids to print an extra space before the newline.
L = [1, 2, 3, 4, 5]
for x in L:
print x,
print
However, in Python 3 it seems that the (supposedly) equivalent code using the print function produces a space after the last number:
L = [1, 2, 3, 4, 5]
for x in L:
print(x, end=" ")
print()
Of course there are easy answers to my question. I know I can use string concatenation:
L = [1, 2, 3, 4, 5]
print(" ".join(str(x) for x in L))
This is a quite good solution, but compared to the Python 2 code I find it counter-intuitive and definitely slower. Also, I know I can choose whether to print a space or not myself, like:
L = [1, 2, 3, 4, 5]
for i, x in enumerate(L):
print(" " if i>0 else "", x, sep="", end="")
print()
but again this is worse than what I had in Python 2.
So, my question is, am I missing something in Python 3? Is the behavior I'm looking for supported by the print function?

You can apply the list as separate arguments:
print(*L)
and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:
>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():
joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string
Note that this requires manual conversion to strings for any non-string values in L!

Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.
The best way is to print joined string of numbers converted to strings.
print(" ".join(list(map(str,l))))
Note that I used map instead of loop.
I wrote a little code of all 4 different ways to compare time:
import time as t
a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
print(i, end=" ")
print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)
Result:
Time 74344.76 71790.83 196.99 153.99
The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.
Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).

list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
print(i, end=', ')
print(list[-1])
do for loops really take that much longer to run?
was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:
spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
print(i, end=', ')
print('and ' + spam[-1])

Joining elements in a list space separated:
word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
joined_string = w + joined_string + " "
print(joined_string.rstrim())

Related

Splitting a joined list of integers to its original form

I'm trying to solve a problem that I'm facing. I wanted to convert a list of integers to a single integer(join all the elements of the list) and then split them to their original form. for example for the code below(assume I have a function that deals with the index of the y and the list) so if put in 'chart' for y
y = list(input("enter name"))
List=[1,2,3,4,5]
for i,p in enumerate(List):
y[i] = p
print('list is'y)
s = int(''.join([str(int) for int in List]))
print('joined form of the list is', s)
def dec():
t = [', '.join([str(int) for int in List])]
print('original form is', t)
dec()
I want the out put to be
List is [1, 2, 3, 4, 5]
joined form of the list is 12345
original form is [1, 2, 3, 4, 5]
instead for the original form I get a single string. How do I solve this?
int is a function in python (it translates the string you give it in an integer). I would advise against using that word to designate a variable, however short lived.
Now, the join method of the string class is a function that returns a string made up of all the elements of an iterator (here, your integer list), seperated by the string. So, what you are doing with that code line :
t = [', '.join([str(int) for int in List])]
is making a list made of one element, the string made up by all the elements in the List, separated by commas.
If you want to convert all the integers to strings and make a list out of that, you should just skip the "join" part :
t = [str(i) for i in yourList]
And if you want to get back an integer list from a string you can do what Corralien or Bruno suggested.
Your code returns a list of 1 element which is a string representation of your list:
>>> [', '.join([str(i) for i in l])]
['1, 2, 3, 4, 5']
Use instead:
l = [1, 2, 3, 4, 5]
# encode from list
n = int(''.join([str(i) for i in l]))
# decode from number
o = [int(i) for i in str(n)]
Output:
>>> l
[1, 2, 3, 4, 5]
>>> n
12345
>>> o
[1, 2, 3, 4, 5]
you can make them all togethrer by making a for loop and multiply previous result with 10 and adding existing digit
# your code goes here
array = [1,2,3,4,5]
result = 0
for digit in array:
result = result*10+digit
print(result)
output
12345
You almost got it right. all you need to do is change t = [', '.join([str(int) for int in List])] to t = [int(i) for i in List]
y = list(input("enter name"))
List=[1,2,3,4,5]
for i,p in enumerate(List):
y[i] = p
print('list is',y)
s = int(''.join([str(int) for int in List]))
print('joined form of the list is', s)
def dec():
t = [int(i) for i in List]
print('original form is', t)
dec()

python - Splitting a list of integers into list of digits

I have a list which contains 8-digit integers, where each integer represents a flag. e.g:
qc = [11221427, 23414732, 144443277,...]
I want to create 8 new variables where first variable is the first digit of all the numbers and so on. e.g:
qc1 = [1,2,1]
qc2 = [1,3,4]
I am able to calculate it using the following code:
qc_str = [str(e) for e in qc]
k,l = 0,0
for item in qc_str:
qc1[k] = int(qc_str[k][l])
qc2[k] = int(qc_str[k][l+1])
qc3[k] = int(qc_str[k][l+2])
qc4[k] = int(qc_str[k][l+3])
qc5[k] = int(qc_str[k][l+4])
qc6[k] = int(qc_str[k][l+5])
qc7[k] = int(qc_str[k][l+6])
qc8[k] = int(qc_str[k][l+7])
k += 1
It takes a lot of time for running on 100,000 rows. Is there a better or faster way of doing it. Any thoughts would be appreciated.
This is one way:
qc = [11221427, 23414732, 144443277]
lst = [list(map(int, i)) for i in zip(*map(str, qc))]
# [[1, 2, 1],
# [1, 3, 4],
# [2, 4, 4],
# [2, 1, 4],
# [1, 4, 4],
# [4, 7, 3],
# [2, 3, 2],
# [7, 2, 7]]
If you really need these as separate variables, either use lst[idx] or a dictionary {i: j for i, j in enumerate(lst, 1)}.
If by faster you meant a lower processing time, you should note that the str() and int() casts are computationally pretty expensive.
You should consider using integer division and modulus to extract the single digits:
k-th digit (from the left) = number / 10^(k-1) % 10
Here some quick dirty code I used to confirm my hypothesis.
import time
l = [x for x in range(1000000,9999999)]
l2 = []
l3 = []
start = time.time()
for x in l:
a = str(x)
l2.append(int(a[-2]))
stop = time.time()
print ("Elasped time: ", stop-start)
start = time.time()
for x in l:
l3.append(x//10 % 10)
stop = time.time()
print("Elapsed time: ", stop-start)
Basically I compare the timings between doing a str() and an int() and extracting the digits using integer division to extract the 2nd digits.
I get the following output:
13.855608940124512
5.115100622177124
That's a 2.5x performance boost.

python last element change to different format

i have a list such as this 1,2,3,4,5,6,7,8,9,10. I want to loop through it with python code, and properly format it to 1,2,3,4,5,6,7,8,9,10. The following is the code that i am using to execute the loop
lst = [1,2,3,4,5,6,7,8,9,10]
for x in lst:
print "%s,"%x
This is the return value
1,2,3,4,5,6,7,8,9,10,
Can python pick up the last element of the loop and change the format of the loop?
You can use join but you will need to change the ints to strings:
print ','.join(str(x) for x in lst)
You can specify a separator and join the list:
print ", ".join(str(x) for x in lst)
Also, I recommend not hiding the builtin name list and call your numbers something else.
If you want to explicitly loop through it, and not print the space:
import sys
my_list = range(1,10+1) 
for x in my_list:
sys.stdout.write("%s," % x)
or
>>> my_list = range(1,10+1)
>>> print ','.join(map(str, my_list)) + ','
where the last + ',' is necessary to have a comma at the very end.
The word list is a builtin in python, so you should avoid naming variables list as that will remove the keyword from the namespace.
>>> a = (1,2,3)
>>> print a
(1, 2, 3)
>>> print list(a)
[1, 2, 3]
>>> type(a) == list
False
>>> type(list(a)) == list
True
Just for fun:
>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> str(lst)[1:-1]
'1, 2, 3, 4, 5, 6, 7, 8, 9, 10'

Python printing without commas

How can I print lists without brackets and commas?
I have a list of permutations like this:
[1, 2, 3]
[1, 3, 2] etc..
I want to print them like this: 1 2 3
blah = [ [1,2,3], [1,3,2] ]
for bla in blah:
print ' '.join(map(str, bla))
It's worth noting that map is a bit old-fashioned and is better written as either a generator or list-comp depending on requirements. This also has the advantage that it'll be portable across Python 2.x & 3.x as it'll generate a list on 2.x, while remain lazy on 3.x
So, the above would be written (using a generator expression) as:
for bla in blah:
print ' '.join(str(n) for n in bla)
Or using string formatting:
for bla in blah:
print '{} {} {}'.format(*bla)
If the list is
l=[1,2,3,4,5]
Printing the list without bracket and commas:
print " ".join(map(str,l))
#1 2 3 4 5
Number_list = [1, 2, 3, 4, 5]
Print(*Number_list, sep="") # empty quote
Example you have a list called names.
names = ["Sam", "Peter", "James", "Julian", "Ann"]
for name in range(len(names)):
print names[name],
In [1]: blah = [ [1,2,3], [1,3,2] ]
In [2]: for x in blah:
...: print x[0],x[1],x[2]
...:
1 2 3
1 3 2
In [3]:
n = int(input())
i = 1
x = []
while (i <= n):
x.append(i)
i = i+1
print(*x, sep='')
assuming n is a number input by a user, you can run through a loop and add the values i to n to a list x. at the end, you can print the array (*x) using nothing ('') to separate the values. this keeps your values in their original format, in this case a number.
You can do this.
Code:
list = [[1, 2, 3], [3, 2, 1]]
for item in list:
print("{}".format(item, end="\n")
Result:
[1, 2, 3]
[3, 2, 1]
completedWord=['s','o','m','e',' ','w','o','r','d','s']
print(*completedWords,sep=' ')
output = s o m e w o r d s
note there are two spaces in sep=' '
temp = [[2,3,5],[2,5,3]]
for each_temp in temp:
if isinstance(each_temp,list):
for nested_temp in each_temp:
print nested_temp

How to convert varying formats of a string into a list of int? (python)

m = re.match(r'(\d+)(?:-(\d+))?$', string)
start = m.group(1)
end = m.group(2) or start
return list(range(int(start, 10), int(end, 10) + 1))
Right now this is able to handle strings in the following format and convert them into a list...
'0-6' results in [0,1,2,3,4,5,6]
'7' results in [7]
Is there anyway I can change the notation to be able to handle strings in the following format as well...
'1 2 3 4 5' results in [1,2,3,4,5]
Regular expressions are not all there is to life. In this case, there's really no reason to use regular expressions. Try this, it's over twice as fast as, for example, Shawn Chin's to_num_list on the sample data '0-6 2 3-6' (for all data I tried on it it was between about 1.9 and 4.5 times as fast):
def included_numbers(s):
out = []
for chunk in s.split():
if '-' in chunk:
f, t = chunk.split('-')
out.extend(range(int(f), int(t)+1))
else:
out.append(int(chunk))
return out
I would stick to the same notation, then use re.findall() to get all matches. Example
import re
def to_num_list(instr):
out = []
for m in re.finditer(r'(\d+)(?:-(\d+))?', instr):
if m.group(2) == None:
out.append(int(m.group(1)))
else:
start = int(m.group(1))
end = int(m.group(2))
out.extend(xrange(start, end + 1))
return out
This will give you the ability to handle imputs such as "1 2 3 10-15" as well. Example usage:
>>> to_num_list("0-6")
[0, 1, 2, 3, 4, 5, 6]
>>> to_num_list("10")
[10]
>>> to_num_list("1 3 5")
[1, 3, 5]
>>> to_num_list("1 3 5 7-10 12-13")
[1, 3, 5, 7, 8, 9, 10, 12, 13]
and skips over erroneous inputs (which may not necessarily be what you want):
>>> to_num_list("hello world 1 2 3")
[1, 2, 3]
>>> to_num_list("")
[]
>>> to_num_list("1 hello 2 world 3")
[1, 2, 3]
>>> to_num_list("1hello2")
[1, 2]
m = re.match(r'(?:(\d+)(?:-(\d+))|(?:(\d+)(?:\s+|$))+)?$', string)
Then, look in the captures for group 3.
The two input formats can be matched by non-greedy regex (designated by the ? quantifier after the *):
m = re.match(r'^(\d+)[0-9\-\s]*?(\d+)?$', string)
Will always extract the first number and last number into m.group(1) and m.group(2) respectively, or if there is only a single number it will be matched in m.group(1)
See greedy vs non-greedy in the python docs.
If you are ok with using a split you can simplify your regex and let the split handle all the space separated list definitions.
import re
def answer(string):
m = re.match(r'(\d+)-(\d+)$', string)
if m:
start = m.group(1)
end = m.group(2) or start
return list(range(int(start), int(end) + 1))
return map(int, string.split(' '))

Categories

Resources