Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
To convert a list to CSV, use the join-function:
>>> lst = [1,2,3,4]
>>> ",".join(str(item) for item in lst)
"1,2,3,4"
If the list already contains only string, you just do ",".join(l).
Your best solution is probably to use the csv module, as suggested elsewhere. However, to answer your question as stated:
Option 1: count your way through using enumerate()
for i, value in enumerate(my_list):
print value,
if i < len(my_list)-1:
print ", followed by"
Option 2: handle the final value (my_list[-1]) outside the loop
for value in my_list[:-1]:
print value, ", followed by"
print my_list[-1]
To convert a list to csv you could use csv module:
import csv
list_of_lists = ["nf", [1,2]]
with open('file', 'wb') as f:
csv.writer(f).writerows(list_of_lists)
The 'file' file would be:
n,f
1,2
actually when a for loop in python ends the name that it bound is still accessible and bound to its last value:
for i in range(10):
if i == 3:
break
print i # prints 3
i use this trick with with like:
with Timer() as T:
pass # do something
print T.format() # prints 0.34 seconds
Not exactly what you want:
>>> for i in range(5):
print(i)
else:
print("Last i is",i)
0
1
2
3
4
Last i is 4
Edited: There is csv module in standard library, or simply ','.join(LIST)
Related
I would like print a result without duplicate with my multiplication
Here an example :
5*3*2=30
2*3*5=30
5*2*3=30
3*2*5=30
.....
All these element are from my list that I browse and you can see it's always =30
So I would like display only the first element (5*3*2) and not others because they are the same.
To be more accurate, here an example what I have :
list = ['5*3*2','5*2*3','2*3*5','2*5*3']
for i in list:
if eval(i) == eval(i)+1 ??? (I dont know how to say the next element)
print(eval(i))
Thanks for reading
Something like this with not in will help you.
#python 3.5.2
list = ['5*3*2','5*2*3','6*9','2*3*5','2*5*3','8*3','9*6']
elm = []
for i in list:
elm_value = eval(i)
if elm_value not in elm:
elm.append(elm_value)
print(elm)
DEMO: https://rextester.com/QKV22875
The comparison:
eval(i) == eval(i)+1
Will compare if the the number i is equal to i + 1, which will always return False. I'm sure you mean to use i as an index and simply wanted to compare if the current element is equal to the next element in the list. However, doing this doesn't really keep track of duplicates, since you have to consider everything else in the list.
Its also not a good idea to use list as a variable name, since it shadows the builtin function list. Plenty of other suitable names you can use.
One way is to use a set to keep track of what items you have seen, and only print items that you have seen for the first time:
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
calc = eval(exp)
if calc not in seen:
print(calc)
seen.add(calc)
If you are always dealing with simple multiplying expressions with the * operator(no brackets), you could also use functools.reduce and operator.mul instead to multiply the numbers instead of eval here. This will first split the numbers by *, map each number string to an integer, then multiply every element with each other.
from operator import mul
from functools import reduce
lst = ["5*3*2","5*2*3","2*3*5","2*5*3"]
seen = set()
for exp in lst:
numbers = map(int, exp.split("*"))
calc = reduce(mul, numbers)
if calc not in seen:
print(calc)
seen.add(calc)
Output:
30
With the following list:
l = ['5*3*2','5*2*3','2*3*5','2*5*3', '2*2']
(Note that list is already something in python so I wouldn't recommend using that as a variable name)
I would first create a list of unique values:
unique_vals = set(map(eval, list))
set([4, 30])
Then for each unique values get the first match in l:
[next(x for x in l if eval(x) == i) for i in unique_vals]
I get:
['2*2', '5*3*2']
Is that what you want?
I'm having trouble displaying my list in a money format ($0000.00)
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range (10):
priceList[i] = random.uniform(1,1000)
print (priceList)
If I try
print ('%.02d' %(priceList))
Python returns
TypeError: %d format: a number is required, not list
You cannot print a list this way, you need to print each list item. A list comprehension works well here:
[print('%.02f' % i) for i in priceList]
You need to put the printing inside your for loop:
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range(10):
priceList[i] = random.uniform(1,1000)
print("${:07.02f}".format(priceList[i]))
In 07.02f, 07 says to make sure that the string is at least 7 characters long. The 0 is there because if the string is less than 7 characters, that is the character to be used to make it 7 characters. 02 before the f means that there should be at least two characters after the decimal point. The 0 is there so that if there are fewer than two characters, it will be used to fill it in.
Because you are trying to do that operation over a list. You need to do it on each element in your list. Try this:
Also, I think you want to use %.02f and not %.02d
print(' '.join('%.02f' % (x) for x in priceList))
Output:
728.08 289.73 117.96 29.70 562.40 255.97 213.55 235.08 436.10 654.54
If you want it just as a list, you can simply do this only:
print(['%.02f' % x for x in priceList])
You should be using proper Python 3 format strings. You can do something like this:
import random
priceList = [1,2,3,4,5,6,7,8,9,10]
for i in range (10):
priceList[i] = random.uniform(1,1000)
moneyList = list(map(lambda x: "${:07.02f}".format(x), priceList))
print(moneyList) # => output:
"""
['$294.90', '$121.71', '$590.29', '$45.52', '$319.40', '$189.03', '$594.63', '$135.24', '$645.56', '$954.57']
"""
for this list ,
l=[i for i in range(1,100)]
How can i restrict to print only 1st 20 elements.
What i am trying to do is ,
>>> counter=0
>>> for index , i in enumerate(l):
... if counter==20:
... break
... print index , i
... counter+=1
...
Is there is another way to do this without using counter variable ?
Use a sliced list, like this
l=[i for i in range(1,100)]
for index, i in enumerate(l[:20]):
print index, i
Or you can use itertools.islice, to avoid generating entire list and instead iterate over xrange as long as you want, like this
from itertools import islice
for index, i in enumerate(islice(xrange(1, 100), 20)):
print index, i
Nishant N.'s answer is the probably the best. But your code would also have worked had you changed your if statement to read
if i == 20:
Just in case you wondered why it wasn't working (also you would have needed to set counter to 0 before the code you posted, but I accept that may just have been omitted.
I'm new to programming with python and programming in general and got stuck wit the following problem:
b=["hi","hello","howdy"]
for i in b:
print i
#This code outputs:
hi
hello
howdy
How can I make it so the iterating variable is an int so it works the following way?
b=["hi","hello","howdy"]
for i in b:
print i
#I want it to output:
0
1
2
The Pythonic way would be with enumerate():
for index, item in enumerate(b):
print index, item
There's also range(len(b)), but you almost always will retrieve item in the loop body, so enumerate() is the better choice most of the time:
for index in range(len(b)):
print index, b[index]
b=["hi","hello","howdy"]
for count,i in enumerate(b):
print count
you could always do this:
b=["hi","hello","howdy"]
for i in range(len(b)):
print i
I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))