python last element change to different format - python

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'

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

extending list without spaces in python

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]

Duplicate number in List remove in python

I just want simple list which remove duplicate digit
a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
m = []
def single_digit_list(a):
return [m.append(x) for x in a if x not in m]
print "New List", single_digit_list(a)
I was expected that new list gave me the one digit in list not repeated but i got following output
New List [None, None, None, None, None, None, None, None, None]
I can't understand what going on
Simple Know what is wrong in code
use set to remove duplicates:
m=set(a)
If you wanted output to be list:
m=list(set(a) )
Your code is good..You just have to return m...instead of returning return value of append...For ex, print m.append(10) will print None which is actually append's return value,you are not printing m.
You could modify you code as follows to return list:
a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
def single_digit_list(a):
m = []
[m.append(x) for x in a if x not in m]
return m #you have appended elements to m
You are trying to return a list of lists where all the lists are None.
This is because m.append() does not return anything and you are trying to create a list of what m.append returns
Just do it as:
def single_digit_list(a):
m = []
for x in a:
if x not in m:
m.append(x)
return m
>>> print single_digit_list([2,3,4,4,4,4,5,6,7,8,9,9,9,9,0])
[2,3,4,5,6,7,8,9,0]
If your list is already grouped, you can use groupby.
>>> x = [1, 1, 4, 4, 4, 5, 2, 2, 2, 3, 3]
>>> from itertools import groupby
>>> print [i[0] for i in groupby(x)]
[1, 4, 5, 2, 3]
This solution does not break order of element instead of converting to set.
The reason why you got list of None value is :
List comprehension is use to generate a list base on the return of the expression given inside the list comprehension.
Eg: [ expression for item in list if conditional ]
So, in your case you are appending an item into a list, which return None after appending the item if it was appending successfully.
Eg:
>>> ls = []
>>> print ls.append('a')
None
>>>
So, at the end of your list comprehension, your list m got the correct unique element list but you return the list generate by the comprehension which is a list of None value.
Conclusion:
You can fix that by return the value of m not the result of list comprehension.
Or here is another easy solution using dictionary key:
>>> a = [2,3,4,4,4,4,5,6,7,8,9,9,9,9,0]
>>> dict.fromkeys(a).keys()
[0, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Using 'not' in a 'for-loop statement'

Why is not possible to use a not in a for statement?
Assuming that both object and list are iterable
If you can't do that is there another way around?
Here is an example, but "obviously" a syntax error:
tree = ["Wood", "Plank", "Apples", "Monkey"]
plant = ["Flower", "Plank", "Rose"]
for plant not in tree:
# Do something
pass
else:
# Do other stuff
pass
Here's one way, using sets and assuming that both objects and list are iterable:
for x in set(objects).difference(lst):
# do something
First of all, you should not call a variable list, that'll clash with a built-in name. Now the explanation: the expression set(objects).difference(lst) performs a set difference, for example:
lst = [1, 2, 3, 4]
objects = [1, 2, 5, 6]
set(objects).difference(lst)
=> set([5, 6])
As you can see, we found the elements in objects that are not in the list.
If objects and list are two lists, and you want to iterate over every element of objects that isn't in list, you want the following:
for object in objects:
if object not in list:
do_whatever_with(object)
This loops over everything in objects and only processes the ones that aren't in list. Note that this won't be very efficient; you could make a set out of list for efficient in checking:
s = set(list)
for object in objects:
if object not in s:
do_whatever_with(object)
It looks like you are confusing a couple of things. The for loop is used to iterate over sequences (lists, tuples, characters of a string, sets, etc). The not operator reverses boolean values. Some examples:
>>> items = ['s1', 's2', 's3']
>>> for item in items:
... print item
...
s1
s2
s3
>>> # Checking whether an item is in a list.
... print 's1' in items
True
>>> print 's4' in items
False
>>>
>>> # Negating
... print 's1' not in items
False
>>> print 's4' not in items
True
If you mean to iterate over a list except few:
original = ["a","b","c","d","e"]
to_exclude = ["b","e"]
for item [item for item in orginal if not item in to_exclude]: print item
Produces:
a
c
d
You may use list comprehension combined with inline if:
>>> lst = [1, 2, 3, 4]
>>> objects = [1, 2, 5, 6]
>>> [i for i in objects if i not in lst]
[5, 6]
And another way:
from itertools import ifilterfalse
for obj in ifilterfalse(set(to_exclude).__contains__, objects):
# do something
Here is a simple way to achieve what you want:
list_i_have = [1, 2, 4]
list_to_compare = [2, 4, 6, 7]
for l in list_i_have:
if l not in list_to_compare:
do_something()
else:
do_another_thing()
Foreach item in the list you have, you can have a exclude list to check it is inside of list_to_compare.
You can also achieve this with list comprehension:
["it is inside the list" if x in (3, 4, 5) else "it is not" for x in (1, 2, 3)]

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

Categories

Resources