Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List iteration
#3
There are multiple ways to solve this problem. It is a bit of a cheat, but a cheat that Python programs should know about.
Output:
>>> string = "3,9,13,4,42" >>> values = eval(string) >>> print(values) (3, 9, 13, 4, 42) >>> help(eval) Help on built-in function eval in module builtins: eval(source, globals=None, locals=None, /) Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
I didn't know if this would work before I tried it. I assumed that running this program would give me a syntax error. But it works too.
values = 1, 2, 3, 4, 5
print(values)
Output:
(1, 2, 3, 4, 5)
Once you have a list of numbers it should be easy to write a for loop or list comprehension to square the values.
Reply


Messages In This Thread
List iteration - by Peca - Nov-11-2020, 08:08 AM
RE: List iteration - by perfringo - Nov-11-2020, 08:46 AM
RE: List iteration - by deanhystad - Nov-11-2020, 05:13 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020