Python printing without commas - python

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

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()

Multiplying every second number in a list

I need to be able to multiply every second number in a list by 2 so say:
List = [1,2,3,4]
I want this to return [1,4,3,8] but all the ways that I have tried it such as
credit_card = [int(x) for x in input().split()]
credit_card[::2] = [x*2 for x in credit_card[::2]]
print(credit_card)
If i input the same list from before it returns [2,2,6,4]
Is there a way to accomplish what I'm trying to accomplish?
You are almost there, you just need to start from the second (1-indexed) element:
credit_card[1::2] = [x*2 for x in credit_card[1::2]]
That said, since you seem to be implementing the Lunh checksum, you only need a sum of those digits without having to update the original data, like done in this example.
lst = [1,2,3,4]
new_lst = [2*n if i%2 else n for i,n in enumerate(lst)] # => [1, 4, 3, 8]
credit_card = input().split()
for x in len(credit_card)
if x % 2 != 0
credit_card[x] = credit_card[x] * 2
print (credit_card)
for i,_ in enumerate(credit_card):
if i%2:
credit_card[i] *= 2
or if you want to be fancy:
credit_card=[credit_card[i]*(2**(i%2)) for i in range(len(credit_card))]
Another solution using enumerate:
[i* 2 if p % 2 else i for p, i in enumerate(l)]
where i is the p-th element of l.
>>> l = [1,2,3,4]
>>>
>>> list(map(lambda x: x*2 if l.index(x)%2 else x, l))
[1, 4, 3, 8]

Print a list of space-separated elements

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())

iterating to nth value in python

How I will iterate for loop in python for 1 to specific value?
I can iterate on list in python like :
for x in l:
print x
But.
If i wanted to iterate from 1 to number th, in matlab I will do :
str = "abcd"
for i=1:z
for j=1:y
if s(:,i)==s(j,:)'
Seq(i)=str(j);
end
end
end
How I will iterate such in python?
for i in range(0, 11):
print i
HTH
To access values in lists, use the square brackets for slicing along with the index.
for x in l[start:end]:
print x
You have a grate post here about slice notation
Another grate link about lists
Example 1:
myList = [1, 2, 3, 4]
for x in myList[:-1]:
print x
Output:
1
2
3
Example 2:
myList = [1, 2, 3, 4]
for x in myList[1:3]:
print x
Output:
2
3
You need to get use to the idea of slicing in python, see Explain Python's slice notation
Non-slicing:
a = [1,2,3,4,5,6,7,8]
n = 5
for i in range(n):
print a[i]
With slices:
a = [1,2,3,4,5,6,7,8]
n = 5
print a[:n]
Use slice notation (This creates temporary list that contains first n items):
>>> s = "abcd"
>>> for x in s[:2]:
... print(x)
...
a
b
or use itertools.islice:
>>> import itertools
>>> for x in itertools.islice(s, 2):
... print(x)
...
a
b

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'

Categories

Resources