Reputation: 75
I'm stuck at a problem where I need a function that takes two arguments, one character and a lists that contains list. The function is then supposed to add that element to all the lists in the list. So if I have the arguments "o"
and [['tesc'], ['fo'], [1]]
the output should be [['tesc', 'o'], ['fo', 'o'], [1, 'o']]
Here's my code, I suspect that I'm not doing anything right as I don't get any output at all
def distribute(e, l):
new_list = []
for i in l:
new_list.append(i)
for e in new_list:
new_list.append(e)
print(new_list)
What am I doing wrong?
Upvotes: 0
Views: 657
Reputation: 20414
You are using the same variable name 'e'
in the for-loop
and as a function
parameter
. Also, in this second loop
, you want to append
to i
as these are the sub lists - not append
to new_list
.
This is why the function
never completes as you are looping
through each element in new_list
but adding to new_list
as you do so so it never ends.
Finally, I would change the print
to return
as you are writing a function
:
def distribute(e, l):
new_list = []
for i in l:
new_list.append(i)
for i in new_list:
i.append(e)
return new_list
This will work, however it is not very pythonic
. All the first for-loop
is doing is creating a copy of the input list ('l')
which is necessary (in some applications) as without it, the input list
would be modified as lists
are immutable
.
However, you could get rid of this loop
altogether by just copying the list
with a slice
. This would make your function more succinct:
def distribute(e, l):
new_list = l[:]
for i in new_list:
i.append(e)
return new_list
And of course, if you do not care if the list
parsed into the function
is modified, you can not bother making a copy of it:
def distribute(e, l):
for i in l:
i.append(e)
return l
Upvotes: 1
Reputation: 123463
You're making things too complicated:
def distribute(e, l):
for sublist in l:
sublist.append(e)
print(l)
distribute("o", [['tesc'], ['fo'], [1]])
Output:
[['tesc', 'o'], ['fo', 'o'], [1, 'o']]
Upvotes: 1
Reputation: 71451
You can try this:
def add_item(l, a):
return [i+[a] for i in l]
print(add_item([['tesc'], ['fo'], [1]], "o"))
Output:
[['tesc', 'o'], ['fo', 'o'], [1, 'o']]
Upvotes: 1