Declare long list in python - python

my_list = [20,21,22 ........ 60]
in python, how can I easily declare above list with 40 elements in it. Instead of typing all the 40 elements. i know for loop can be used to append to a different list. but is there any easiest way ?

If you want a list of this specific type, you can just use
my_list = list(range(20, 61))
or if the definition becomes more complex, you can use list comprehension, like
my_list = [i*i for i in range(10, 20)]

The solution is to define a range (default step size is 1 like in your example) and transform it to a list. Make sure that the last value in range() is the last value you want +1.
mylist = list(range(20,61))

You can apply for-loop combined with range()-function in your code in order to append elements to my_list.
my_list = [20] # Initial list
for i in range(21, 61):
my_list.append(i) # Append elements
Verify that there are 41 elements in your list (from 20 to 60)
if len(my_list) == 41:
print(True)
else:
print(False)

Related

Pandas: create a list from the printed output of a for-loop [duplicate]

My actual example is more involved so I boiled the concept down to a simple example:
l = [1,2,3,4,5,6,7,8]
for number in l:
calc = number*10
print calc
For each iteration of my loop, I end up with a variable (calc) I'd like to use to populate a new list. My actual process involves much more than multiplying the value by 10, so I'd like to be able to set each value in the new list by this method. The new code might look like this:
l = [1,2,3,4,5,6,7,8]
for number in l:
calc = number*10
# set calc as x'th entry in a new list called l2 (x = iteration cycle)
print l2
Then it would print the new list: [10,20,30,40,...]
There are several options...
List comprehensions
Use list comprehension, if short enough:
new_list = [number * 10 for number in old_list]
map()
You could also use map(), if the function exists before (or you will eg. use lambda):
def my_func(value):
return value * 10
new_list = map(my_func, old_list)
Be aware, that in Python 3.x map() does not return a list (so you would need to do something like this: new_list = list(map(my_func, old_list))).
Filling other list using simple for ... in loop
Alternatively you could use simple loop - it is still valid and Pythonic:
new_list = []
for item in old_list:
new_list.append(item * 10)
Generators
Sometimes, if you have a lot of processing (as you said you have), you want to perform it lazily, when requested, or just the result may be too big, you may wish to use generators. Generators remember the way to generate next element and forget whatever happened before (I am simplifying), so you can iterate through them once (but you can also explicitly create eg. list that stores all the results).
In your case, if this is only for printing, you could use this:
def process_list(old_list):
for item in old_list:
new_item = ... # lots of processing - item into new_item
yield new_item
And then print it:
for new_item in process_list(old_list):
print(new_item)
More on generators you can find in Python's wiki: http://wiki.python.org/moin/Generators
Accessing "iteration number"
But if your question is more about how to retrieve the number of iteration, take a look at enumerate():
for index, item in enumerate(old_list):
print('Item at index %r is %r' % (index, item))
Here's how to do it without jumping straight into list comprehensions. It's not a great idea to use l as a variable name because it is identical to 1 in some fonts, so I changed it (althought l1 isn't really much better :) )
l1 = [1,2,3,4,5,6,7,8]
l2 = []
for number in l1:
calc = number*10
print calc
l2.append(calc)
list comprehensions do provide a more compact way to write this pattern
l2 = [ number*10 for number in l1 ]
Use a list comprehension :
>>> l = [1,2,3,4,5,6,7,8]
>>> l2 = [ item*10 for item in l]
>>> l2
[10, 20, 30, 40, 50, 60, 70, 80]
Which is roughly equivalent to, but a list comprehension is faster than normal for-loop:
>>> l2 = []
>>> for number in l:
... calc = number * 10 #do some more calculations
... l2.append(calc) #appends the final calculated value at the end of l2
...
>>> l2
[10, 20, 30, 40, 50, 60, 70, 80]
You can also create a function for all the calculations you're doing, and then call the function inside the list comprehension :
def solve(x):
#do some calculations here
return calculated_value
l2 = [ solve(item) for item in l]
So I believe you would like to apply a function to every element of the list.
Have you tried a list comprehension?
[num*10 for num in l]
Should give you what you need for this simple example.
Naturally, if you have some more complex set of operations you can use a function you defined earlier, to wit:
def explode(n):
return (n + (n * n) - (3 * n))
[explode(num) for num in l]
A simple answer to your problem would be to append calc to a list as shown below:
l = [1,2,3,4,5,6,7,8]
your_list = []
for number in l:
calc = number*10
your_list.append(calc)
To access variables in the list, use slicing syntax.
ie, the 2nd element in a list would be your_list[1], the 5th your_list[4].
I suspect you'll need to empty the list at some point. To do so with slicing, use calc[:] = []
Everyone else has given you the right answer: use a list comprehension.
I will give you an alternate right answer: Use map with a lambda or a function.
You can use a lambda when the 'function' is very simple:
print map(lambda x: x*10,[1,2,3,4,5,6,7,8])
# [10, 20, 30, 40, 50, 60, 70, 80]
The function used by map can be of arbitrary complexity, and then it is easier use a function:
def more_complex(x):
# can be as complex as a function can be
# for now -- *10
return x*10
print map(more_complex,[1,2,3,4,5,6,7,8])
But that would work with a comprehension as well:
l2=[more_complex(x) for x in [1,2,3,4,5,6,7,8]]
Just so that you are familiar with the form of map vs list comprehension.
loop that generates the list
KOT = []
l = [1,2,3,4,5,6,7,8]
for number in l:
calc = number*10
KOT.append(calc)
You get the KOT list
KOT = [10, 20, 30, 40, 50, 60, 70, 80]

Check list to see if element greater than specified number [duplicate]

This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 4 years ago.
I'm trying to check if a specific element in the list is greater than a set value.
So
x=22
list=[10,20,30]
# check if anything in list is greater than x
# do something to the list
I'm just not sure what commands to use in this scenario to check every list element or if it's even possible in one line.
Use any, Python's natural way of checking if a condition holds for, well, any out of many:
x = 22
lst = [10, 20, 30] # do NOT use list as a variable anme
if any(y > x for y in lst):
# do stuff with lst
any will terminate upon the first truthy element of the iterable it is passed and, thus, not perform any spurious iterations which makes it preferable to max or list comprehension based approaches that have to always iterate the entire list. Asymptotically however, its time complexity is, of course, still linear.
Also, you should not shadow built-in names like list.
You ask for "if any element in the list is greater than x". If you just want one element, you could just find the greatest element in the list using the max() function, and check if it's larger than x:
if max(list) > x:
...
There's also a one-liner you can do to make a list of all elements in the list greater than x, using list comprehensions (here's a tutorial, if you want one):
>>> x = 22
>>> list = [10, 20, 30, 40]
>>> greater = [i for i in list if i > x]
>>> print(greater)
[30, 40]
This code generates a list greater of all the elements in list that are greater than x. You can see the code responsible for this:
[i for i in list if i > x]
This means, "Iterate over list and, if the condition i > x is true for any element i, add that element to a new list. At the end, return that new list."
You could use filter and filter your list for items greater than 22, if
the len of this filtered list is > 0 that means your original list contains a value larger than 22
n = 22
lst = [10,20,30]
if len(list(filter(lambda x: x > n, lst))) > 0:
# do something to lst
List comprehension would suit your use case.
In [1]: x=22
In [2]: l=[10,20,30]
In [3]: exist = [n for n in l if n > x]
In [4]: if exist:
...: print "elements {} are greater than x".format(exist)
...:
elements [30] are greater than x
If your list is very long, use generator so that you do not have to iterate through all elements of the list.
In [5]: exist = next(n for n in l if n > x)
In [6]: if exist:
print "Element {} is greater than x".format(exist)
...:
Element 30 is greater than x

How to generate new list from variable in a loop?

My actual example is more involved so I boiled the concept down to a simple example:
l = [1,2,3,4,5,6,7,8]
for number in l:
calc = number*10
print calc
For each iteration of my loop, I end up with a variable (calc) I'd like to use to populate a new list. My actual process involves much more than multiplying the value by 10, so I'd like to be able to set each value in the new list by this method. The new code might look like this:
l = [1,2,3,4,5,6,7,8]
for number in l:
calc = number*10
# set calc as x'th entry in a new list called l2 (x = iteration cycle)
print l2
Then it would print the new list: [10,20,30,40,...]
There are several options...
List comprehensions
Use list comprehension, if short enough:
new_list = [number * 10 for number in old_list]
map()
You could also use map(), if the function exists before (or you will eg. use lambda):
def my_func(value):
return value * 10
new_list = map(my_func, old_list)
Be aware, that in Python 3.x map() does not return a list (so you would need to do something like this: new_list = list(map(my_func, old_list))).
Filling other list using simple for ... in loop
Alternatively you could use simple loop - it is still valid and Pythonic:
new_list = []
for item in old_list:
new_list.append(item * 10)
Generators
Sometimes, if you have a lot of processing (as you said you have), you want to perform it lazily, when requested, or just the result may be too big, you may wish to use generators. Generators remember the way to generate next element and forget whatever happened before (I am simplifying), so you can iterate through them once (but you can also explicitly create eg. list that stores all the results).
In your case, if this is only for printing, you could use this:
def process_list(old_list):
for item in old_list:
new_item = ... # lots of processing - item into new_item
yield new_item
And then print it:
for new_item in process_list(old_list):
print(new_item)
More on generators you can find in Python's wiki: http://wiki.python.org/moin/Generators
Accessing "iteration number"
But if your question is more about how to retrieve the number of iteration, take a look at enumerate():
for index, item in enumerate(old_list):
print('Item at index %r is %r' % (index, item))
Here's how to do it without jumping straight into list comprehensions. It's not a great idea to use l as a variable name because it is identical to 1 in some fonts, so I changed it (althought l1 isn't really much better :) )
l1 = [1,2,3,4,5,6,7,8]
l2 = []
for number in l1:
calc = number*10
print calc
l2.append(calc)
list comprehensions do provide a more compact way to write this pattern
l2 = [ number*10 for number in l1 ]
Use a list comprehension :
>>> l = [1,2,3,4,5,6,7,8]
>>> l2 = [ item*10 for item in l]
>>> l2
[10, 20, 30, 40, 50, 60, 70, 80]
Which is roughly equivalent to, but a list comprehension is faster than normal for-loop:
>>> l2 = []
>>> for number in l:
... calc = number * 10 #do some more calculations
... l2.append(calc) #appends the final calculated value at the end of l2
...
>>> l2
[10, 20, 30, 40, 50, 60, 70, 80]
You can also create a function for all the calculations you're doing, and then call the function inside the list comprehension :
def solve(x):
#do some calculations here
return calculated_value
l2 = [ solve(item) for item in l]
So I believe you would like to apply a function to every element of the list.
Have you tried a list comprehension?
[num*10 for num in l]
Should give you what you need for this simple example.
Naturally, if you have some more complex set of operations you can use a function you defined earlier, to wit:
def explode(n):
return (n + (n * n) - (3 * n))
[explode(num) for num in l]
A simple answer to your problem would be to append calc to a list as shown below:
l = [1,2,3,4,5,6,7,8]
your_list = []
for number in l:
calc = number*10
your_list.append(calc)
To access variables in the list, use slicing syntax.
ie, the 2nd element in a list would be your_list[1], the 5th your_list[4].
I suspect you'll need to empty the list at some point. To do so with slicing, use calc[:] = []
Everyone else has given you the right answer: use a list comprehension.
I will give you an alternate right answer: Use map with a lambda or a function.
You can use a lambda when the 'function' is very simple:
print map(lambda x: x*10,[1,2,3,4,5,6,7,8])
# [10, 20, 30, 40, 50, 60, 70, 80]
The function used by map can be of arbitrary complexity, and then it is easier use a function:
def more_complex(x):
# can be as complex as a function can be
# for now -- *10
return x*10
print map(more_complex,[1,2,3,4,5,6,7,8])
But that would work with a comprehension as well:
l2=[more_complex(x) for x in [1,2,3,4,5,6,7,8]]
Just so that you are familiar with the form of map vs list comprehension.
loop that generates the list
KOT = []
l = [1,2,3,4,5,6,7,8]
for number in l:
calc = number*10
KOT.append(calc)
You get the KOT list
KOT = [10, 20, 30, 40, 50, 60, 70, 80]

Indices are not synchronous of using one lists indices in another

Coming from R, this was hard to grasp. Taking elements from a list start with position 0.
The problem is that using one list to select items from another list are not running at the same pace here.
list1 = [1,2,3,4]
list2 = [1,2,3,4]
for x in range(0, len(list1)):
print(list1[list2[x]])
This will result in:
>> 2
>> 3
>> 4
>> IndexError: list index out of range
When I put an extra item in the start of list1, and added an item at the end of list2, the problem stops (simply because they are not synchronous like this).
Obviously I am not familiar with the language yet, what would be the correct way to use values from one list to select values from another?
Is this the correct way to think of it?
for x in range(0, len(list1)):
print(list1[list2[x]-1])
Python is 0-index based. seq[0] is the first element in seq.
R is 1-index based.
So, yes, in python you could use
list1 = [1,2,3,4]
list2 = [1,2,3,4]
for x in range(0, len(list2)):
print(list1[list2[x]-1])
The range should go up to len(list2), not len(list1).
Also, range(0, len(list2)) is the same as range(len(list2)). When
range is passed only one argument, it is interpreted as the stop
value, with a start value of 0 taken by default.
Note that in Python
for x in range(...):
can often be avoided, and if so, is preferable. Instead, you can write
for item in list2:
print(list1[item-1])
and item will be assigned to each of the items in list2.
If your list has 4 items, your indexes must run from 0 to 3, so using the value 4 throws an error. Here's an example with letters which might make it clearer:
list1 = [0,2,1,3]
list2 = ['a','a','d','m']
for x in list1:
print(list2[x]),
=> a d a m

Searching for substring in element in a list an deleting the element

I have a list and I am trying to delete the elements that have 'pie' in them. This is what I've done:
['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
if "pie" in list[i]:
del list[i]
I keep getting list index out of range, but when I change the del to a print statement it prints out the elements fine.
Instead of removing an item from the list you're iterating over, try creating a new list with Python's nice list comprehension syntax:
foods = ['applepie','orangepie', 'turkeycake']
pieless_foods = [f for f in foods if 'pie' not in f]
Deleting an element during iteration, changes the size, causing IndexError.
You can rewrite your code as (using List Comprehension)
L = [e for e in L if "pie" not in e]
Something like:
stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]
Modifying an object that you're iterating over should be considered a no-go.
The reason to why you get a error is because you change the length of the list when you delete something!
Example:
first loop: i = 0, length of list will become 1 less because you delete "applepie" (length is now 2)
second loop: i = 1, length of list will now become just 1 because we delete "orangepie"
last/third loop: i = 2, Now you should see the problem, since i = 2 and the length of the list is only 1 (to clarify only list[0] have something in it!).
So rather use something like:
for item in in list:
if "pie" not in item:
new list.append(item)
Another but longer way would be to note down the indexes where you encounter pie and delete those elements after the first for loop

Categories