This question already has answers here:
How do I iterate through two lists in parallel?
(8 answers)
Closed 7 years ago.
So I need to append two list together. Each element of the List one attached to each element of List two. So it the final list will be something like this: ['L1[0]L2[0]','L1[1]L2[1]','L1[2]L2[2]','L1[3]L2[3]']. I keep running into the problem of putting a for loop inside another for loop but the result is having the first loop element repeat multiple times. I understand this isn't working, if any one can give me a nudge or somewhere to look into information on this sort of subject. As always thank you for the help!! Here is my code:
def listCombo(aList):
myList=['hello','what','good','lol','newb']
newList=[]
for a in alist:
for n in myList:
newList.append(a+n)
return newList
Example:
List1=['florida','texas','washington','alaska']
List2=['north','south','west','east']
result= ['floridanorth','texassouth','washingtonwest','','alaskaeast']
You need to use zip.
[i+j for i,j in zip(l1, l2)]
Example:
>>> List1=['florida','texas','washington','alaska']
>>> List2=['north','south','west','east']
>>> [i+j for i,j in zip(List1, List2)]
['floridanorth', 'texassouth', 'washingtonwest', 'alaskaeast']
list comprehension over zip:
[x[0]+x[1] for x in zip(list1,list2)]
>>> [x[0]+x[1] for x in zip(['1','2','3'],['3','4','5'])]
# ['13', '24', '35']
Related
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 3 years ago.
Currently I have a list of lists
l=[['asd'],['fgd']].
I want to turn it into a list
goal_list=['asd','fgd']
but I do not know how to turn a list into the value inside it - does anyone have an idea how to this efficiently?
This is a perfect use-case for itertools.chain, where we essentially chain all sublists together to flatten them!
from itertools import chain
def single_list(arr):
return list(chain(*arr))
print(single_list([['asd'],['fgd']]))
print(single_list([['asd', 'abcd'],['fgd', 'def']]))
The output will be
['asd', 'fgd']
['asd', 'abcd', 'fgd', 'def']
Just use a list comprehension with two loops:
goal_list = [item for sublist in l for item in sublist]
This question already has answers here:
Different ways of clearing lists
(8 answers)
Closed 4 years ago.
list1 = [2,5,61,7,10]
list1.remove(list1[0:len(list1)-1])
print(list1)
I want to remove all elements from that list but it shows me syntax error.
Any idea how can I remove all elements and print the final result like []
To remove all list items just use the in-built .clear() function:
>>> list1 = [2,5,61,7,10]
>>> list1.clear()
>>> print(list1)
[]
>>>
If you want to remove all elements from a list, you can use the slice assignment:
list1[:] = []
But with list.remove(), you can only do it one-by-one:
for item in list(list1):
list1.remove(item)
Note I created a copy of list1 with the for loop because it's dangerous to modify what you're iterating over, while it's safe to modify the list while iterating over a copy of it.
To remove some of the items:
for item in list1[0:3]:
list1.remove(item)
Or just better yet, use slice assignment:
list1[0:3] = []
This question already has answers here:
Ellipsis lists [...] and concatenating a list to itself [duplicate]
(3 answers)
Closed 6 years ago.
I have a list X = ['xyz']
I use the below commands for appending to another variable.
L = X
L.append(X)
L
Out[109]: ['xyz', [...]]
I am unable to understand why the second element in the new L list is not having the value as 'xyz'
My question is not how to append or extend a list, but in fact about the functionality of Append function, which has been correctly explained by #sinsuren below.
append add X as an element to L. If you want the element inside X to be inserted to L, use extend instead:
>>> X = ['xyz']
>>> L = X
>>> L.extend(X)
>>> L
['xyz', 'xyz']
Try this, it will extend the list.
L.extend(X)
But if you want to use append. Use a element like this L.append('abc'). It will give same result or L.append(X[0])
Edit: You have Appended list to itself. It will recursively append to itself and due to which even L[1] will give you same response. Like L[1] = ['xyz', [...]] . and for more understanding Please refer What's exactly happening in infinite nested lists?
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 7 years ago.
I have a list
test_list = [1,2,3,4,5]
I want to iterate over the elements of this list and delete them after using. But when I try to do this
for element in test_list:
print element
test_list.remove(element)
Alternate elements are printed and removed from test_list
1
3
5
print test_list
[2, 4]
Please explain why this happens!
Read the answers to strange result when removing item from a list to understand why this is happening.
If you really need to modify your list while iterating do this:
>>> items = ['x', 'y', 'z']
>>> while items:
... item = items.pop()
... print item
...
z
y
x
>>> items
[]
Note that this will iterate in reverse order.
in python this concept is called an iterator
my_iter = iter(my_list)
each time you consume or look at an element it becomes gone ...
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 10 years ago.
I have an array of array in python. What is the best way to convert it to an array in python?
for example:
m = [[1,2],[3,4]]
# convert to [1,2,3,4]
I am new in python, so I dont know any solution of it better than writing a loop. Please help.
Use itertools.chain or list comprehension:
from itertools import chain
list(chain(*m)) # shortest
# or:
list(chain.from_iterable(m)) # more efficient
For smaller lists comprehension is faster, for longer ones chain.from_iterable is more suitable.
[item for subl in m for item in subl]
For understanding the nested comprehension, you can split it across multiple lines and compare it to a regular for loop:
[item #result = []
for subl in m #for subl in m:
for item in subl] # for item in subl:
# result.append(item)