repeat the elements in a list - python

so this is my list:
my_list = [['a','b','c'],['d','e','f']]
I want to have the output that times 2 times each:
final_list = [['a','a','b','b','c','c'],['d','d','e','e','f','f']]
And this is what I am doing:
final_list = []
for new_list in my_list:
for my_new_list in new_list:
for i in range(2):
final_list.append(my_new_list)
but it shows:
final_list = ['a','a','b','b','c','c','d','d','e','e','f','f']
how do I fix it? and by the way I wish to do it with for loop. Thank you

This will only work for parsing an array of arrays, which I assume should be enough:
final_list = []
for sublist in my_list:
temp_list = []
for item in sublist:
temp_list += [item] * 2
final_list.append(temp_list)

def change(L):
res = []
for i in L:
temp = []
for j in i:
temp.append(j)
temp.append(j)
res.append(list)
return res

Related

complex list comprehension syntax

Just to know if it is possible to write this in a line comprehension and if it is, how to write it.
lst1 = [0,1,2,3,4,5,6,7,8,9,10]
lst2 = [[0,4],[1,5],[2,6],[3,7]]
list3 = []
list4 = []
list5 = []
for l in lst1:
for k in lst2:
if l == k[0]:
list3.append(k)
elif l==k[1]:
list4.append(k)
else:
list5.append(l)
print('lst1',lst1)
print('lst2',lst2)
print('list3',list3)
print('list4',list4)
print('list5',list5)
You can generally turn a nested for loop that builds a list into a list comprehension by using the same exact for ... in statements in the same order:
list3 = [k for l in lst1 for k in lst2 if l == k[0]]
list4 = [k for l in lst1 for k in lst2 if l == k[1]]
list5 = [l for l in lst1 for k in lst2 if l not in k]

Python, create a list of lists from a base list and list of sub-list lengths [duplicate]

How to make function that can execute list comprehension(zip?) The sublists should have different lengths which are given.
Example:
myList = [1,2,3,4,5,6,7,8,9]
myNum = (2,4,3)
Desired outcome:
newList = ['(1,2)', '(3,4,5,6)', '(7,8,9)']
If it does not have to be a List comprehension, you can solve it like this:
myList = [1,2,3,4,5,6,7,8,9]
myNum = (2,4,3)
prev = 0
newList = []
for i in myNum:
newList.append(tuple(myList[prev:prev+i]))
prev = prev+i
try this one:
myList = [1,2,3,4,5,6,7,8,9]
myNum = (2,4,3)
newList = []
for i in myNum:
newList.append(tuple(myList[:i]))
[ myList.pop(myList.index(x)) for x in myList[:i] ]
print(newList)
OR
myList = [1,2,3,4,5,6,7,8,9]
myNum = (2,4,3)
newList = []
x = 0
for i in myNum:
if x == 0:
newList.append(tuple(myList[:i]))
x = myList[:i][-1]
else:
end_index = myList[myList.index(x)+1 : myList.index(x)+1+i]
newList.append(tuple(end_index))
x = end_index[-1]
print(newList)

Taking a list and printing all of the indexes of the elements that aren't equal to 0

I have to take a list such as [2,2,0,2] and I then need to return a new list of the indexes for the elements in the list that are not 0 so for the list of [2,2,0,2] I would need to return [0,1,3]. Or for [1,0,1,1] I would need to return [0,2,3].
def test(B):
for k in list(B):
if k > 0:
result = []
for i in range(len(B)):
result.append(i)
return result
test([2,2,0,2])
->[0,1,2,3]
My issue is that all of the indexes get returned and I have tried to fix this but have had no luck. If anyone could help that'd me great, thanks.
You can use enumerate to achieve this neatly:
def legal(B):
return [i for i, x in enumerate(B) if x]
# or if you want to cover more than numbers
# return [i for i, x in enumerate(B) if x != 0]
>>> legal([2,2,0,2])
[0, 1, 3]
>>> legal([1,0,1,1])
[0, 2, 3]
this should do the work :
def indices(some_list):
indices_list = []
for i in range(0, len(some_list)):
if some_list[i] != 0:
indices_list.append(i)
return indices_list
you can use list comprehension like below
ls = [2,2,0,2]
ind = [i for i, val in enumerate(ls) if val!=0]
print(ind)
You could try this:
def legal(B):
result = []
for i, k in enumerate(list(B)):
if k > 0:
result.append(i)
return result
Why are you doing list(B)? If B is not a list then this should work. If it is you should remove the list function.

how to check item in a list contains in python

I have 2 lists,
my_list = ['on#3','one',"$", "lo#"]
spl = ["#","$"]
I am trying to get the items in 'my_list' which contains any of the items in spl.
I tried
out_list = [item for item in my_list if item.contains("!".join(spl))]
but this gives error.
My expected output is
out_list = ["on#3","$"]
No such method as item.contains. There's item.__contains__, but you don't need to call that directly.
You want to check if any of the items in spl is contained in the item, use the builtin any:
lst = [item for item in my_list if any(x in item for x in spl)]
# ... if any(item.__contains__(x) for x in spl)]
print(lst)
# ['on#3', '$']
result = [item for item in my_list for s in spl if s in item]
And more human readable form:
result = []
for item in my_list:
for s in spl:
if s in item:
result.append(item)

Compare two python lists and expand the shorter list to the length of the longer list

The question header I have is a little confusing and I just wasn't sure how too explain it well with just the header.
I have two lists.
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
Expected output:
new_list = [10,0,0,40,0,0,70,0,0]
How should I do this? The following is what I have and I wasn't sure what was wrong:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
for j in to_be_expand_list:
if i == j:
expanded_list.append(j)
else:
if expanded_list[-1] != 0:
expanded_list.append(0)
return expanded_list
Try something like this:
def expand_list(full_list, short_list):
return [x if x in short_list else 0 for x in full_list]
This uses a list comprehension to generate a list which is the length of the complete list, but contains only those elements which were in the short list, replacing all the rest with zeroes.
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
new_list = list_1[:]
for i, v in enumerate(list_1):
if v not in list_2:
new_list[i] = 0
print new_list
result:
[10, 0, 0, 40, 0, 0, 70, 0, 0]
This checks the positions in list_1 which aren't in list_2, and sets them to 0
You are going over all the to_be_expand_list for each item on the complete_list and in (almost) each iteration you append an item, so at the end you will have len(list1)*len(list2) items.
You should change it to:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
if i in be_expand_list:
expanded_list.append(i)
else:
expanded_list.append(0)
return expanded_list
If you look for simpler approach you can use list comprehension:
[x if x in list2 else 0 for x in list1]

Categories