This question already has answers here:
Get the nth element from the inner list of a list of lists in Python [duplicate]
(1 answer)
Slicing list of lists in Python
(6 answers)
Closed 5 months ago.
i have list in python. For example Test=[[1,1],[1,2],[1,3],[1,4]].
Now i would like to create a 1D-List by removing every first number to get this: [1,2,3,4].
My current Code works just fine, however it is definitely not the most pythonic code.
Could anyone give me a better code for the following? Perhaps a small explenation would be great, as i would like to understand how to programm in good pythonic code. :)
i=len(Test)
b=[]
a=0
for x in range (100):
Test[a].remove(Test[a][0])
b+=Test[a]
a+=1
print(b)
greeting, Dominik
Test=[[1,1],[1,2],[1,3],[1,4]]
# Loop through list using list comprehension and select the second
# item
Test2 = [i[1] for i in Test]
print(Test2)
Using a list comprehension:
test = [[1, 1], [1, 2], [1, 3], [1, 4]]
output = [x[1] for x in test]
print(output) # [1, 2, 3, 4]
Related
This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 1 year ago.
I have a list of lists that contain a list at the end. If this list has more than one element, I want to duplicate the entry and for each with the individual value without being in the list.
E.g.
[[1, [1,2]] -> [[1, 1][1, 2]]
There's probably a much more efficient solution than the one I've tried, but I'd like to understand why you're giving me the mistakes you're giving.
First, even though it indicates that it is not the same list, it is changing the value in both lists. Second, when I create the second element, it changes the previous one as well. Any explanation is welcome. Thanks
Variables in Python are just references. I recommend making a copy by using a slice. l_copy = l_orig[:]
When I first saw the question (pre-edit), I didn't see any code, so I did not have the context. It looks like you're copying the reference to that row. (Meaning it actually points to the sub-lists in the original.)
new_list.append(row[:])
Weird right? Look at the following example
lst1 = [1,2,3]
#bad copy example
_
lst2 = lst1
-
lst2.append(4)
print(lst1,lst2)
You would expect that only lst2 should have 4, but no. lst1 and lst2 both have 4.
[1, 2, 3, 4] [1, 2, 3, 4]
So to avoid a problem like this, we can use list2 = list1.copy()
lst1 = [1,2,3]
lst2 = lst1.copy()
lst2.append(4)
print(lst1,lst2)
output
[1, 2, 3] [1, 2, 3, 4]
This question already has answers here:
Iterating over every two elements in a list [duplicate]
(22 answers)
Closed 3 years ago.
I have a list [1,2,3,4,5,6] and I want to iterate over it like
[1,2]
[3,4]
[5,6]
I am able to find a lot of answers using zip() that result in
[1,2]
[2,3]
[3,4]
[4,5]
[5,6]
and I could create a new list from this and iterate over every 2nd element in that list with [::2] but I am wondering if there is a more elegant solution.
Thanks for your help.
Using zip with a stride of [::2] is the most concise way I can think to achieve this.
>>> data = [1,2,3,4,5,6]
>>> pairs = [[i,j] for i,j in zip(data[::2], data[1::2])]
>>> pairs
[[1, 2], [3, 4], [5, 6]]
You don't need zip, you can achieve what you want with a simple generator like this:
def pairs(iterable):
for i in range(0, len(iterable), 2):
yield iterable[i:i+2]
Another solution that does not require iterable to be indexable or have a known length, and therefore is more general, is to use iter():
def pairs(iterable):
it = iter(iterable)
while True:
yield next(it), next(it)
This will automatically stop when next() raises StopIteration to indicate that the iterable doesn't have any more items.
In both of the cases you can then do:
for a, b in pairs([1,2,3,4,5,6]):
print(a, b)
This question already has answers here:
list comprehension with multiple conditions (python)
(2 answers)
Closed 3 years ago.
I'd like to use a single line expression to create a list of lists with an if condition from three other lists. I use the zip method for this. It's working fine, just not in a single line.
check = [3,2]
a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10,11,12]
# working
my_list = []
for a,b,c in zip(a,b,c):
if a in check:
my_list.append( [a,b,c] )
# not working
# my_list = [ [a,b,c] if a in check for a,b,c in zip(a,b,c) ]
print(my_list)
Output
[[2, 6, 10], [3, 7, 11]]
I get "invalid syntax" for "a: list" after the for keyword in the single line expression. Did i miss something?
You put the condition in the wrong place. It goes at the end in comprehensions.
my_list = [[a,b,c] for a,b,c in zip(a,b,c) if a in check]
This question already has answers here:
Wrapping around a list as a slice operation
(4 answers)
Closed 6 years ago.
I want to swap the consecutive elements of a list such that the first element will go to the last. eg [4, 7, 3, 4, 3] should print as [7,3,4,3,4]
This is the code I've written but it doesn't work right. How can I modify it to get it working?
ls = [4, 7, 3, 4, 3]
i=0
b=1
while i+1<len(ls):
ls[i]=a
ls[i]=ls[i+1]
ls[i+1]=a
i+=1
print ls
I do not want to just switch the first element with the last one. I want to modify this code further to create a bubble sort algorithm, I am just confused at how to get done what I just explained.
Updated : Thanks for the answer that I should change "ls[i]=a" with "a=ls[i]", but can someone explain to me how this differs in logic?
You don't need a loop to move the first element to the last. Just pop the first element off the list, then append it.
ls.append(ls.pop(0))
Python allows to work with lists by selecting one or several elements at the time and to concatenate the content of the list
ls = [4, 7, 3, 4, 3]
new_list_with_first_element_at_the_end = ls[1:] + [ls[0]]
If you really feel you must, make a swap function:
def swap(l, i, j):
tmp = l[j]
l[j] = i
l[i] = tmp
Then you can:
for i in range(len(l)-1):
swap(l, i, i+1)
This question already has answers here:
Get unique values from a list in python [duplicate]
(30 answers)
Closed 6 years ago.
I have recently started trying to learn Python, and I try to improve the way I write code, and make it more "Pythonic".
Therefore, it would really be nice if someone could explain to me if the following can be formulated more elegantly.
Hopefully this is not a duplicate (I checked, but you never know)
I have a list of 5 elements, and I want to return specific elements.
Let's say for example that I have [1, 2, 3, 3, 4].
I already have a function double(list), that if a list element exists twice returns that element (in this case 3).
I would like to generate from this list a tuple that contains the numbers that are exist only once (1, 2, 4).
One option is the following:
Run the double(list) function and get the value of the element that is double.
Create an empty tuple
Iterate over the list items, and if the value is not equal to what the double(list) function returned, add it to the tuple
Return the tuple.
My question is: is there a more elegant/Pythonic way of doing this?
(in one line, using maybe a more complex expression?)
Thanks in advance
The general way to do this is to make a set out of the elements and then count them, or just use collections.Counter, then go through the list and include only the appropriate elements, by either creating an empty list and then adding to it with a traditional loop or by using a comprehension with a filter.
>>> import collections
>>> l = [1, 2, 3, 3, 4]
>>> c = collections.Counter(l)
>>> new_list = [item for item in l if c[item] < 2]
>>> new_list
[1, 2, 4]
Since you want a single-line solution (well except for the actual list declaration of course :) ):
your_list = [1, 2, 3, 3, 4]
uniques = [item for item in your_list if your_list.count(item) == 1]
I would use collections.Counter for that:
>>> import collections
>>> l = [1, 2, 3, 3, 4]
>>> c = collections.Counter(l)
>>> [el for el in l if c[el] == 1]
[1, 2, 4]