I need to receive the first element of a list with a command line argument, and 2nd element to be the value of the 1st element plus one, third element to be the value of the 2nd element plus 1 and so on.
For example:
$ python3 print_list5.py 6
[6, 7, 8, 9, 10]
$ python3 print_list5.py 0
[0, 1, 2, 3, 4]
I think I can improve the code by using for loops, but I am not sure how to use it.
My code:
Expected result:
Don't use for loops, use range instead
range will return an generator that generates values from an initial_value to a final_value increasing by a step_value on demand.
You can then convert this generator into a list which will execute the generation of the elements and give a list with the desired elements as a result.
first_elem = sys.argv[1]
n_elems = 5
print(list(range(first_elem, first_elem + n_elems)))
If you want the number of elements to also be a parameter do
first_elem = sys.argv[1]
n_elems = sys.argv[2]
print(list(range(first_elem, first_elem + n_elems)))
and then call your script as
$ python3 print_list5.py 2 5
where in this case 2 is the first element and 5 the number of elements
A simple way to achieve it using for loops is:
import sys
my_list = [int(sys.argv[1])]
list_length = 5
for x in range(list_length-1):
my_list.append(my_list[-1] + 1)
print(my_list)
Use for x in range(nElem) to iterate nElem times
Use list.append() to append into the list the last element of the same list (list[-1])
Here is the result:
This is the optimized solution, I use list comprehension works like a charm.
List comprehension creates a new list based on existing ones.
import sys
input_sys = int(sys.argv[1])
print([input_sys if i == input_sys else i for i in range(input_sys, input_sys + 5)])
Related
sum=[1,2,3,4,5,6,7,8,9]
for figure in sum:
print(list(sum))
print(figure)
sum.remove(min(sum))
print(figure)
print(list(sum))
print('\n')
print(list(sum))
You can't change the length of the iterable while iterating over it. If you want to print the minimum item and delete it until the list is empty, you should loop on the condition of the list beein empty, something like this:
sum=[1,2,3,4,5,6,7]
while sum:
print(min(sum))
sum.remove(min(sum))
output:
1
2
3
4
5
6
7
The problem of changing the iterable length is that python's interpreter basically will try to get the next element based on the previous position on the list.
For example, if you loop trough:
[a,b,c,d]
the first item will be a (the item on index 0). The next iteration of the for loop it will try to retrieve the item on index 1 but if you remove a, the ìndex 1 will not be b anymore, because your current list will look like this;
[b,c,d]
and the index 1is now c, skipping every other item on neext iterations
if you want to clear the whole list, the use the inbuilt function clear(). below is the example how to do that.
lis=[1,2,3,4,5,6,7,8,9]
print('printing original list',lis,sep=' : ')
# output printing original list : [1, 2, 3, 4, 5, 6, 7, 8, 9]
lis.clear()
print('printing new cleared list',lis,sep=' : ')
# output printing new cleared list : []
I've had a look through the forums and can't find anything to do with multiplying all elements in an array recursively.
I've created the following code that almost does what I want. The goal is to use no loops and only recursion.
Here's the code:
def multAll(k,A):
multAllAux(k,A)
return A[:]
def multAllAux(k,A):
B = [0]
if A == []:
return 0
else:
B[0] = (A[0] * k)
B.append(multAllAux(k,A[1:]))
return B
print(multAllAux(10, [5,12,31,7,25] ))
The current output is:
[50, [120, [310, [70, [250, 0]]]]]
However, it should be:
[50,120,310,70,250]
I know I am close, but I am at a complete loss at this point. The restrictions of no loops and solely recursion has left me boggled!
Your multAllAux function returns a list. If you append a list to another list, you get this nested list kind of structure that you are getting right now.
If you instead use the "extend" function; it will work as expected.
>>> a = [1, 2, 3]
>>> a.extend([4, 5])
>>> a
[1, 2, 3, 4, 5]
extend takes the elements from a second list and adds them to the first list, instead of adding the second list itself which is what append does!
Your function also returns a zero at the end of the list, which you don't need. You can try this:
def mult(k, A: list) -> list:
return [k * A[0]] + mult(k, A[1:]) if A else []
The problem is here:
B.append(multAllAux(k,A[1:])))
What .append(..) does is it takes the argument, considers it as a single element and adds that element to the end of the list. What you want is to concatenate to the list (ie the item being added should be seen as a list of elements rather than one single element).
You can say something like: B = B + multAllAux(..) or just use +=
B += multAllAux(...)
BTW, if you wanted to multiply a single number to a list, there is a very similar construct: map(..). Note that this behaves slightly differently depending on whether you're using Py2 or Py3.
print(map(lambda x: x * 10, [5,12,31,7,25]))
append will add an item to the end of the list.
l = [1,2,3,4]
l.append(5)
outputs
[1, 2, 3, 4, 5]
now instead of adding 5 at the end of the list I would like to add it to a random location in the list. let's say 5 is being added to index 2. Number 3 will move one index forward.
[1,2,5,3,4]
You could use insert method of list.
import random
l = [1,2,3,4]
l.insert(random.randint(0, len(l)), 5)
First argument of the method is index, the second argument is value. See documentation.
Use Insert where first argument is index (position), 2nd is value
l.insert(2, 5)
I'm writing a program that keeps asking the user to enter names until the word END is entered, at which point it prints out the list of names in reverse order.
At first, I didn't know how to print out a list in reverse order, so I found this: Traverse a list in reverse order in Python
I decided to use the reversed() built-in function:
import getpass
import time
import sys
print("Welcome " + getpass.getuser() + "...")
time.sleep(0.25)
print("This program, powered by Python, it will ask you to enter names...")
time.sleep(0.5)
print("...once you have finished, enter END to print off your list")
names = []
while True:
name = input("Please enter a name: ")
if name == "END":
print(reversed(names))
sys.exit()
names.append(name)
However, all it prints is:
<list_reverseiterator object at 0x0000000002A14F28>
Why is this happening and how can I tackle this issue?
Many thanks
reversed returns an iterator that will iterate the list in a reversed order. It will not return a reversed list. This is an important difference because if it returned a reversed list, then that list would have to be allocated in memory. So you would end up with a copy of it; and you would have to iterate over it twice (once for creating the reversed list, and then once for printing it).
Instead reversed just begins iterating at the end of the original list. You can easily see this if you modify the list after creating the reversed iterator:
>>> a = [1,2,3,4,5]
>>> r = reversed(a)
>>> a[2:2] = [10, 11, 12, 13]
>>> a
[1, 2, 10, 11, 12, 13, 3, 4, 5]
>>> list(r)
[12, 11, 10, 2, 1]
The reversed iterator just remembered the index where it would start iterating (i.e. index 4). With the modified list, this no longer is the end of the list though.
So, if you want to have a copied list in reversed order, you will have to call list on it, to create one from it. Otherwise, if you can, you should really just try to iterate on the reversed iterator.
For the sake of efficiency, reversed returns an iterator object instead of a full list. This way, it doesn't have to allocate any additional space, or do much work at all, until the user starts iterating through it.
As pointed out by behzad, the easiest way to get your results in list form is to use list.
>>> seq = [1,2,3]
>>> x = reversed(seq)
>>> print list(x)
[3, 2, 1]
The reversed method does not return a list. Instead this returns an iterator. Iterators are objects that allows you to iterate over lists, dicts and any object that is iterable. Thus you need either to use it with a loop or convert it to list as #behzad.nouri suggested:
for item in reversed(names):
print item
From http://docs.python.org/release/2.4.3/whatsnew/node7.html
Reverse Iteration:
A new built-in function, reversed(seq), takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order.
>>> for i in reversed(xrange(1,4)):
... print i
...
3
2
1
use print list(reversed(names)) at the your method to print the list.
Fixed Code:
import getpass
import time
import sys
print("Welcome " + getpass.getuser() + "...")
time.sleep(0.25)
print("This program, powered by Python, it will ask you to enter names...")
time.sleep(0.5)
print("...once you have finished, enter END to print off your list")
names = []
while True:
name = input("Please enter a name: ")
if name == "END":
print list((reversed(names)))
sys.exit()
names.append(name)
Output Example:
['fxvb', 'asd', 'asd']
reversed(seq) is a built-in function. Takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order.
>>> x = [1, 2, 3, 4, 5]
>>> for a in reversed(x):
... print a
...
5
4
3
2
1
I would suggest using slicing - it's much more efficient
print(names[::-1]
For a list of 30 strings it is about 3 times faster
In [99]: %timeit names[::-1]
1000000 loops, best of 3: 264 ns per loop
In [103]: %timeit list(reversed(names))
1000000 loops, best of 3: 839 ns per loop
Beginner here, learning python, was wondering something.
This gives me the second element:
list = [1,2,3,4]
list.index(2)
2
But when i tried this:
list = [0] * 5
list[2] = [1,2,3,4]
list.index[4]
I get an error. Is there some way to pull the index of an element from an array, no matter what list it's placed into? I know it's possible with dictionaries:
info = {first:1,second:2,third:3}
for i in info.values:
print i
1
2
3
Is there something like that for lists?
The index method does not do what you expect. To get an item at an index, you must use the [] syntax:
>>> my_list = ['foo', 'bar', 'baz']
>>> my_list[1] # indices are zero-based
'bar'
index is used to get an index from an item:
>>> my_list.index('baz')
2
If you're asking whether there's any way to get index to recurse into sub-lists, the answer is no, because it would have to return something that you could then pass into [], and [] never goes into sub-lists.
list is an inbuilt function don't use it as variable name it is against the protocol instead use lst.
To access a element from a list use [ ] with index number of that element
lst = [1,2,3,4]
lst[0]
1
one more example of same
lst = [1,2,3,4]
lst[3]
4
Use (:) semicolon to access elements in series first index number before semicolon is Included & Excluded after semicolon
lst[0:3]
[1, 2, 3]
If index number before semicolon is not specified then all the numbers is included till the start of the list with respect to index number after semicolon
lst[:2]
[1, 2]
If index number after semicolon is not specified then all the numbers is included till the end of the list with respect to index number before semicolon
lst[1:]
[2, 3, 4]
If we give one more semicolon the specifield number will be treated as steps
lst[0:4:2]
[1, 3]
This is used to find the specific index number of a element
lst.index(3)
2
This is one of my favourite the pop function it pulls out the element on the bases of index provided more over it also remove that element from the main list
lst.pop(1)
2
Now see the main list the element is removed..:)
lst
[1, 3, 4]
For extracting even numbers from a given list use this, here i am taking new example for better understanding
lst = [1,1,2,3,4,44,45,56]
import numpy as np
lst = np.array(lst)
lst = lst[lst%2==0]
list(lst)
[2, 4, 44, 56]
For extracting odd numbers from a given list use this (Note where i have assingn 1 rather than 0)
lst = [1,1,2,3,4,44,45,56]
import numpy as np
lst = np.array(lst)
lst = lst[lst%2==1]
list(lst)
[1, 1, 3, 45]
Happy Learning...:)
In your second example, your list is going to look like this:
[0, 0, [1, 2, 3, 4], 0, 0]
There's therefore no element 4 in the list.
This is because when you set list[2], you are changing the third element, not updating further elements in the list.
If you want to replace a range of values in the list, use slicing notation, for example list[2:] (for 'every element from the third to the last').
More generally, the .index method operates on identities. So the following will work, because you're asking python where the particular list object you inserted goes in the list:
lst = [0]*5
lst2 = [1,2,3,4]
lst[2] = lst2
lst.index(lst2) # 2
The answer to your question is no, but you have some other issues with your code.
First, do not use list as a variable name, because its also the name of the built-in function list.
Secondly, list.index[4] is different than list.index(4); both will give errors in your case, but they are two different operations.
If you want to pull the index of a particular element then index function will help. However, enumerate will do similar to the dictionary example,
>>> l=['first','second','third']
>>> for index,element in enumerate(l):
... print index,element
...
output
0 first
1 second
2 third