Python Forum

Full Version: Working with lists homework
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Define 2 lists. The first one must contain the integer values 1, 2 and 3 and the second one the string values a, b and c. Iterate through both lists to create another list that contains all the combinations of the A and B elements. The final list should look like one of the 2 lists:
1. [1a, 1b, 1c, 2a, 2b, 2c, 3a, 3b, 3c]
2. [a1, a2. a3, b1, b2, b3, c1, c2, c3]
BONUS: Make the final list contain all possible combinations : [1a, a1, 1b, b1, 1c, c1, 2a, a2, 2b, b2, 2c, c2, 3a, a3, 3b, b3, 3c, c3]

Help me !
This is not how it works. We are not going to do your homework for you. You need to make effort, post your code in python tags, if you get error, post full traceback in error tags and ask specific questions.
Also,in the future make your thread titles more descriptive.
No problem, friend!
>>> import itertools
>>> a = 'abc'
>>> b = '123'
>>> items = list(map("".join, itertools.product(a, b)))
>>> items
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
>>> bonus = items + [item[::-1] for item in items]
>>> bonus
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3', '1a', '2a', '3a', '1b', '2b', '3b', '1c', '2c', '3c']
(Mar-29-2018, 03:18 PM)nilamo Wrote: [ -> ]No problem, friend!
>>> import itertools
>>> a = 'abc'
>>> b = '123'
>>> items = list(map("".join, itertools.product(a, b)))
>>> items
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
>>> bonus = items + [item[::-1] for item in items]
>>> bonus
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3', '1a', '2a', '3a', '1b', '2b', '3b', '1c', '2c', '3c']

Define two lists and the first one must contain integers. Join will fail
Do you know how to define a list?
if not then here:
list_entry = ["Here ", "is ", "How ", "We", "Make ", "A ", "List"] #Defines a list.

for i in range(0, len(list_entry)):
    print(list_entry[i]) #Prints the list.
P.S. it does not want to make this look like code...

Paste this into your IDE and run it to see how it works.
(Apr-04-2018, 05:12 AM)groovydingo Wrote: [ -> ]
for i in range(0, len(list_entry)):
    print(list_entry[i]) #Prints the list.

OP, and others finding this later, please don't do this. It's not pythonic, and is actively bad practice for iterating over lists. Just iterate over them directly, ie:
for entry in list_entry:
    print(entry)