Python Forum
How to manipulate between lists and get results
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to manipulate between lists and get results
#9
I think it's good to show the pythonic way.

spams = [2, 4, 2, 5]
eggs = [6, 4, 3, 2]
for spam, egg in zip(spams, eggs):
    print(spam, egg)
Read this: https://docs.python.org/3/library/functions.html#zip
To get an index, you can use enumerate.

If you have two lists with different sizes and want to have a default value, use itertools.zip_longest(*iterables, fillvalue=None).

zip_longest example:
from itertools import zip_longest


spams = [2, 4, 2, 5, 5, 6, 7, 1, 4, 5, 6]
eggs = [6, 4, 3, 2]
for spam, egg in zip_longest(spams, eggs, fillvalue=1):
    # 1 is the neutral element in multiplication or division
    # 0 is the neutral element in addition or subtraction
    print(f"{spam} * {egg} = {spam * egg}")
The f-string f"{spam} * {egg} = {spam * egg}" is new in Python 3.6.
It gives us one more method to format strings.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: How to manipulate between lists and get results - by DeaD_EyE - Mar-07-2018, 07:39 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Using an integer to manipulate a string/text variable rexyboy2121 1 1,835 Apr-22-2020, 01:37 AM
Last Post: michael1789

Forum Jump:

User Panel Messages

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