reversed() vs. xrange() [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to traverse a list backwards. I read about xrange() and reversed(). Which one is more expensive?

You can use Python's timeit library to time things like this. You don't say what kind of list you have, so I am assuming a simple list of strings. First I create a list 100 items long and then time both:
my_list = ["hello"] * 100
def v1():
for x in my_list[::-1]:
pass
def v2():
for x in reversed(my_list):
pass
print timeit.timeit(v1)
print timeit.timeit(v2)
This gives the following result:
2.78170533583
2.13084949985
As you can see, in this example reversed() is a bit faster.

xrange() produces a sequence of numbers. You can then use those numbers as list indices if you want, or you can use them for anything where you want those numbers.
for i in xrange( len(l)-1, -1, -1):
item = l[i]
print item
reversed() produces the items from something that has a length and can be indexed.
for item in reversed(l):
print item
I would use reversed() because it makes you code shorter, simpler, clearer, and easier to write correctly.

Related

List Comprehension starting at a specific number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I was trying to create this [80000, 104000, 135000...] list in Python. Its the value, starting at 80,000 multiplied by 1.3 each time I want
What i've tried:
a = [num*1.5 for num in ??? if num>=80000] #???--> i've tried range(10)
I should be able to do this but I can't find any solutions rn..
I must use list-comprehensions, if possible.
Some help would be nice, thank you!
There is a very basic mathematical operation that represents multiplying by the same value many time: power.
a = [80000 * (1.3**n) for n in range(100)]
You could write your own generator then use that in conjunction with a list comprehension.
def numgen(start, factor, limit):
for _ in range(limit):
yield int(start)
start *= factor
mylist = [value for value in numgen(80_000, 1.3, 10)]
print(mylist)
Output:
[80000, 104000, 135200, 175760, 228488, 297034, 386144, 501988, 652584, 848359]
import numpy as np
print(80000 * 1.3**np.arange(3))
# [ 80000. 104000. 135200.]

I need to convert the given list of String format to a single list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
need to convert this list :
a = ["['0221', '02194', '02211']"]
type = list
to this list :
a = ['0221', '02194', '02211']
type = list
If your new to python this code would seem like very complicated, but i will explain whats in this piece of code:
a=["['0221', '02194', '02211']"]
a1=[]
nums_str=""
for i in a:
for j in i:
try:
if j=="," or j=="]":
a1.append(nums_str)
nums_str=""
nums=int(j)
nums_str+=str(nums)
except Exception as e:
pass
else:
a=a1.copy()
print(a)
print(type(a))
Steps:
Used for loop to read the content in list a.
Then again used a for loop to read each character in the string of i.
Then used try to try if i can typecast j into int so that it would only add the numbers to nums_str.
Then appended the nums_str to the list a1 if j if = "," or "]".
Continued the above process on each item in a.
After the for loop gets over, i change a to copy of a1.
You can use astliteral_eval to convert strings to Python data structures. In this case, we want to convert the first element in the list a to a list.
import ast
a = ast.literal_eval(a[0])
print(a)
# ['0221', '02194', '02211']
Note: Python built-in function eval also works but it's considered unsafe on arbitray strings. With eval:
a = eval(a[0]) # same desired output
You can try list comprehension:
a = a[0][2:][:-2].split("', '")
output:
a = ['0221', '02194', '02211']

What does this Python syntax do? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
New to python and trying to understand what does following syntax doing ?
def testMissingConfig(self):
""" if config is missing, the config is valid """
input_args = self.buildmock()
validation_errors = [
x
for x in self.validator.validate(
ValidatorArguments(input_args=input_args)
)
if x
]
validation_keys = {x.key for x in validation_errors}
self.assertEmpty(validation_keys)
Especially the array initialization for "validation_errors"
It is called List comprehension. Here you can combine assignments, loops, functions all in one block.
One of the big advantages of list comprehension is that they allow developers to write less
code that is often easier to understand.
Syntax:
[expression for item in list]
Example:
number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
Here the numberlist loops over 0 to 20 and gives even numbers 0,2,4...20 as result.
Similarly in your code, validation_errors will store x if x exists(not null)
Lambda functions can also be used to create and modify lists in less lines of code.
Reference:
https://www.programiz.com/python-programming/list-comprehension

Python map element with character [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am new to python and i am trying to understand the map() function. Is there a better way of doing this
map(lambda x: x+"+" ,map(str,range(5)))
output : ['0+', '1+', '2+', '3+', '4+']
You can use the format-Method directly as map-argument:
map("{}+".format, range(5))
For most tasks like this, it is preferable to use a list comprehension, like so:
[str(i) + '+' for i in range(5)]
Here, you are constructing a list with each element depending only on the number i. Using str(i) + '+' is then one way to build the elements that you want. Another is '{} +'.format(i), but that is beside the point of using a list comprehension.
map vs. list comprehension
The map function is functionally equivalent to a restricted use of the list comprehension syntax. Consider the following generic examples, which will produce the same output:
list(map(fun, iterable))
[fun(el) for el in iterable]
In your example, you construct the function fun right there inside the map call using a lambda expression. The additional list() call is necessary in Python 3, as map returns a generator and not a list.
output = ['{}+'.format(i) for i in range(5)]
print output
['0+', '1+', '2+', '3+', '4+']
As you said you want in Map, You can map something like this:
print(list(map(lambda x:str(x)+'+',range(5))))
output:
['0+', '1+', '2+', '3+', '4+']
Additional info :
map() is a function with two arguments :
map(g, iterable)
first argument function is a function and the second a sequence.
Python 3 map is equivalent to the generator expression
(g(x) for x in iterable)

element that appear more that once in the list in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Please help (I know that it's a silly question):
I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once?
To exclude items from the list that appear more than once:
d = [x for x in d if d.count(x) == 1]
For the example provided above, d will bind to an empty list.
Others have posted good solutions to remove duplicates.
Convert to a set then back again:
list(set(d))
If order matters, you can pass the values through a dict that remembers the original indices. This approach, while expressible as a single expression, is considerably more complicated:
[x for (i, x) in sorted((i, x) for (x, i) in dict((x, i) for (i, x) in reversed(list(enumerate(d)))).iteritems())]
Of course, you don't have to use comprehensions. For this problem, a fairly simple solution is available:
a = []
for x in d:
if x not in a:
a.append(x)
Note that both the order-preserving solutions assume that you want to keep the first occurrence of each duplicated element.
Lets say you got a list named Words and a list UniqueWords, start a loop on Words, on each iteration you check if the list UniqueWords contains the iterated element, if so then continue, if not then add it to the UniqueWords. In the end you will have a list without duplicates. Another way you could do is a loop in a loop and instead of adding you'd remove it if it was found more than once :)
I bet there are far more efficient ways though.
If you're not worried about the order, d = list(set(d))).
If order matters check out the unique_everseen function in the itertools recpies documentation. It give a relatively clean iterator-based solution.
If order doesn't matter, convert to a set.
If you shouldn't have done that already, make sure to read the python docs on itertools, especially product(), permutations() and combinations().

Categories