This question already has answers here:
How to add an integer to each element in a list?
(12 answers)
Closed last month.
I would like to get such a result [2,4,5,6,7], how can do that? Now i get this: [7]
list1 = [1,3,4,5,6]
for i in range(len(list1)):
l = []
# list1[i] = list1[i] + 1
s = list1[i] + 1
l.append(s)
print(l)
you can use list comprehension
list1 = [1,3,4,5,6]
newlist = [x+1 for x in list1]
print(newlist)
If you want to use a loop, you need to put l = [] ahead of it - otherwise you're reintializing it as an empty list at each loop iteration,
list1 = [1,3,4,5,6]
l = []
for el in list1:
l.append(el + 1)
print(l)
Notice that this code directly loops through elements of list1. This is a preferred way for lists and any other iterables. I recommend you use it whenever practical/possible.
As an alternative to list comprehensions and loops, you can also use a map with a lambda,
list1 = [1,3,4,5,6]
new_list = list(map(lambda x: x+1, list1))
print(new_list)
Note, however, that in most situations, including this one, list comprehension is a better choice. For reasons and details, look up this post.
This will work:
list1 = [1,3,4,5,6]
for i in range(len(list1)):
list1[i]+=1
print(list1)
Related
This question already has answers here:
Common elements comparison between 2 lists
(14 answers)
Closed last year.
I have this code:
list1 = [1,2,3]
list2 = [3,4,5]
list3 = []
for i, j in zip(list1,list2):
if i==j:
list3 = i,j
How can I make list3 store elements that are the same between list1 and list2?
An easy way using Python's set intersection:
list1 = [1,2,3]
list2 = [3,4,5]
list3 = list(set(list1).intersection(list2))
print(list3)
or using a for loop:
list1 = [1,2,3]
list2 = [3,4,5]
list3 = []
for i in list1:
if i in list2:
list3.append(i)
print(list3)
I have two lists of tuples, say,
list1 = [('item1',),('item2',),('item3',), ('item4',)] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
Expected output: 'item4' # Item that doesn't exist in list2
As shown in above example I want to check which item in tuples in list 1 does not exist in first index of tuples in list 2. What is the easiest way to do this without running two for loops?
Assuming your tuple structure is exactly as shown above, this would work:
tuple(set(x[0] for x in list1) - set(x[0] for x in list2))
or per #don't talk just code, better as set comprehensions:
tuple({x[0] for x in list1} - {x[0] for x in list2})
result:
('item4',)
This gives you {'item4'}:
next(zip(*list1)) - dict(list2).keys()
The next(zip(*list1)) gives you the tuple ('item1', 'item2', 'item3', 'item4').
The dict(list2).keys() gives you dict_keys(['item1', 'item2', 'item3']), which happily offers you set operations like that set difference.
Try it online!
This is the only way I can think of doing it, not sure if it helps though. I removed the commas in the items in list1 because I don't see why they are there and it affects the code.
list1 = [('item1'),('item2'),('item3'), ('item4')] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
not_in_tuple = []
OutputTuple = [(a) for a, b in list2]
for i in list1:
if i in OutputTuple:
pass
else:
not_in_tuple.append(i)
for i in not_in_tuple:
print(i)
You don't really have a choice but to loop over the two lists. Once efficient way could be to first construct a set of the first elements of list2:
items = {e[0] for e in list2}
list3 = list(filter(lambda x:x[0] not in items, list1))
Output:
>>> list3
[('item4',)]
Try set.difference:
>>> set(next(zip(*list1))).difference(dict(list2))
{'item4'}
>>>
Or even better:
>>> set(list1) ^ {x[:1] for x in list2}
{('item4',)}
>>>
that is a difference operation for sets:
set1 = set(j[0] for j in list1)
set2 = set(j[0] for j in list2)
result = set1.difference(set2)
output:
{'item4'}
for i in list1:
a=i[0]
for j in list2:
b=j[0]
if a==b:
break
else:
print(a)
I have a list that contains duplicates, some are exactly the same while others have just a prefix at the beginning.
For example the following entries refer to the same entry:
'user01', 'aa-user01', 'xyz-user01'
I succeeded to remove the entries that are exactly the same but not the ones with a prefix:
list = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
list2 = []
for i in range(0, len(list)):
if list[i] not in list2:
list2.append(list[i])
print(list2)
I get this:
['user01', 'aa-user01', 'user02', 'user03', 'xyz-user02']
The resulat that i want:
['user01', 'user02', 'user03']
The simplest fix would only consider the token after the "-":
for x in list:
user = x.rsplit("-", 1)[-1]
if user not in list2:
list2.append(user)
Note: you should not shadow built-in names like list. Also, contains-checks are expensive for lists, so if you have lots of data, you should consider using a set or dict.
s = set(x.rsplit("-", 1)[-1] for x in lst)
Docs:
str.rsplit
for i in range(0, len(list)):
if list[i][list[i].find("user"):] not in list2:
list2.append(list[i])
list1 = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
list2 = []
for i in range(0, len(list1)):
if list1[i] not in list2:
list2.append(list1[i])
list2 = list(dict.fromkeys(list2))
print(list2)
print(list2)
One way to do this would be to first remove the prefix using a list comprehension;
Remove prefix
list = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
list = [i.split('-', 1)[-1] for i in l]
list2 = []
for i in range(0, len(list)):
if list[i] not in list2:
list2.append(list[i])
print(list2)
You can go with a short list comprehension, including:
lower() -> Ignore case typing (remove if not needed)
split() -> Removes the prefix
set() -> Removes duplicates
Your result will be set([x.lower().split('-', 1)[-1] for x in test_list]) while test_list is your list.
my_list = ['user01','user01', 'aa-user01','user02','user02', 'user03', 'xyz-user02']
new_list = [j.split('-')[1] if len(j.split('-'))==2 else j for j in my_list]
['user01', 'user01', 'user01', 'user02', 'user02', 'user03', 'user02']#value of new_list
set(new_list)#output unique values
{'user01', 'user02', 'user03'}
I want to make one large list for entering into a database with values from 4 different lists. I want it to be like
[[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]], etc.....]
Another issue is that currently the data is received like this:
[ [ [list1[0], list1[1], [list1[3]]], [[list2[0]]], etc.....]
I've tried looping through each list using indexs and adding them to a new list based on those but it hasn't worked, I'm pretty sure it didn't work because some of the lists are different lengths (they're not meant to be but it's automated data so sometimes there's a mistake).
Anyone know what's the best way to go about this? Thanks.
First list can be constructed using zip function as follows (for 4 lists):
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]
list4 = [13,14,15,16]
res = list(zip(list1,list2,list3,list4))
For arbitrtary number of lists stored in another list u can use *-notation to unpack outer list:
lists = [...]
res = list(zip(*lists))
To construct list of lists for zipping from you data in second issue use flatten concept to it and then zip:
def flatten(l):
res = []
for el in l:
if(isinstance(el, list)):
res += flatten(el)
else:
res.append(el)
return res
auto_data = [...]
res = list(zip(*[flatten(el) for el in auto_data]))
Some clarification at the end:
zip function construct results of the smallest length between all inputs, then you need to extend data in list comprehension in last code string to be one length to not lose some info.
So if I understand correctly, this is your input:
l = [[1.1,1.2,1.3,1.4],[2.1,2.2,2.3,2.4],[3.1,3.2,3.3,3.4],[4.1,4.2,4.3,4.4]]
and you would like to have this output
[[1.1,2.1,3.1,4.1],...]
If so, this could be done by using zip
zip(*l)
Make a for loop which only gives you the counter variable. Use that variable to index the lists. Make a temporary list , fill it up with the values from the other lists. Add that list to the final one. With this you will et the desired structure.
nestedlist = []
for counter in range(0,x):
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
If all the 4 lists are the same length you can use this code to make it even nicer.
nestedlist = []
for counter in range(0,len(firstlist)): #changed line
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
This comprehension should work, with a little help from zip:
mylist = [i for i in zip(list1, list2, list3, list4)]
But this assumes all the list are of the same length. If that's not the case (or you're not sure of that), you can "pad" them first, to be of same length.
def padlist(some_list, desired_length, pad_with):
while len(some_list) < desired_length:
some_list.append(pad_with)
return some_list
list_of_lists = [list1, list2, list3, list4]
maxlength = len(max(list_of_lists, key=len))
list_of_lists = [padlist(l, maxlength, 0) for l in list_of_lists]
And now do the above comprehension statement, works well in my testing of it
mylist = [i for i in zip(*list_of_lists)]
If the flatten concept doesn't work, try this out:
import numpy as np
myArray = np.array([[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]]])
np.hstack(myArray)
Also that one should work:
np.concatenate(myArray, axis=1)
Just for those who will search for the solution of this problem when lists are of the same length:
def flatten(lists):
results = []
for numbers in lists:
for output in numbers:
results.append(output)
return results
print(flatten(n))
I want to add a value to a list of lists.
For input of [[1,2],[2,3]]
I want output of [[2,3],[3,4]]
I can do it with loops:
list_of_lists = [[1,2],[2,3]]
output = []
for list in list_of_lists:
sub_output = []
for value in list:
sub_output.append(value+1)
output.append(sub_output)
print(output)
Can I do this with list comprehension?
If I do:
[value + 1 for list in list_of_lists for value in list]
It gives me [2,3,3,4]. Can I get it to keep the sublist format somehow?
Try...
[ [n + 1 for n in inner_list] for inner_list in list ]
Yeah, you need a nested comprehension:
[[item + 1 for item in list] for list in list_of_lists]
Another way would be to use map:
map(lambda l: map(lambda i: i + 1, l), list_of_lists)
You need to nest a comprehension into that comprehension. Unpack each sublist to make it easier.
[[a+1, b+1] for a,b in list_of_lists]