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
#1
I have 2 lists
Number1 = [13,15,79,15,16]
Number2 = [5,6,7,8]

i want to multiply/divide/add the numbers between Number1 and Number2 lists using for loop. How can i do that
Reply
#2
What have you tried? Post the code (in Python code tags) and we can assist if you get errors or wrong results.
Reply
#3
i am clueless on how to access the data across two lists
Reply
#4
(Mar-07-2018, 02:09 PM)pythoneer Wrote: i am clueless on how to access the data across two lists
well, that is not true, given your previous thread
actually there is enough info in that thread to solve also this problem.
Reply
#5
i am not able to get this right every time and that is why i told i am clueless :(
Reply
#6
You have several lists, all of the same size. You want to do something with an element of those lists, all at the same position of the lists. Therefore, use an index.
Reply
#7
Any example code would be helpful :)
Reply
#8
>>> spams = [2, 4, 2, 5]
>>> eggs = [6, 4, 3, 2]
>>> for index in range(len(spams)):
...   left = spams[index]
...   right = eggs[index]
...   print("Index: {0}  Items: {1}|{2}".format(index, left, right))
...
Index: 0  Items: 2|6
Index: 1  Items: 4|4
Index: 2  Items: 2|3
Index: 3  Items: 5|2
Reply
#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
#10
Actually, the lists are different sizes.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using an integer to manipulate a string/text variable rexyboy2121 1 1,858 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