Create and add a new array - python

I have a while loop that pulls down values and prints them individually. How can I get these individually printed values into one array? Ideally I would put something in my while loop and continuously add to an array with my numeric values.

If you want to do this in a for loop:
valuesToBePulledDown = [1,2,3,4,5,6,7,8,9]
array=[i for i in valuesToBePulledDown]
print array

Use a list comprehension:
print [i for i in xrange(100)]
If you want to iterate over a specific list:
my_list = [4,3,2,1,5,3,2]
print [i for i in my_list]
Maybe you would like to do something to each value before adding it to the list:
my_list = [1,2,3,4,5]
print [i*i for i in my_list] # prints [1,4,9,16,25]
This should get you started.
However, if you are insistent on using a while loop:
count = 0
my_values = []
while count < 10:
my_values.append(count)
count += 1
print my_values # prints [0,1,2,3,4,5,6,7,8,9]
Although, if you want to use an explicit looping construct, this particular scenario lends itself to a for loop:
my_values = []
for i in xrange(10):
my_values.append(i)
print my_values # prints [0,1,2,3,4,5,6,7,8,9]
Needless to say, as with the list comprehensions, you can use any iteratable object, not just xrange() in for loop.

I think that you wanted to say "append" instead of "print", and "list" instead of "array".
valuesToBePulledDown = [1,2,3,4,5,6,7,8,9]
array = []
i = 0
while i<len(valuesToBePulledDown):
array.append(i)
print i
i += 1
By the way, I would recomend you to use a for loop instead a "while", but that's what you asked for.

Related

How can I remove all the numbers in a list except for 1 number (Python)?

I want my code to remove every single number in a list except for a specific number, which is 3. Instead it removes certain numbers but majority of them still remain in the list.
myList = [0,1,2,3,4,5]
i = 0
for i in myList:
print(i)
if i != 3:
myList.remove(i)
else:
continue
i += 1
print(myList)
You've got a few issues. First, you're trying to modify the list in place, as you're trying to process it. You can fix that by changing:
for i in myList:
to:
for i in myList[:]:
That will allow your code to give the desired result. It makes a "copy" of the list over which to iterate, so you can modify the original list without messing up your iteration loop.
The other thing to note is that you assign a value to i in the for loop, but then you manually change it after your if-else block. That change gets discarded when you go back to the top of the loop.
Also, you're else: continue prevents incrementing i, but it doesn't matter, because that incremented value was just getting tossed anyway.
So... commenting out some of the unnecessary stuff gives:
myList = [0,1,2,3,4,5]
# i = 0
for i in myList[:]:
print(i)
if i != 3:
myList.remove(i)
# else:
# continue
# i += 1
print(myList)
You have a couple of problems. First, the for loop iterates the list values, not its index. You can use enumerate to get both the index and the value. Second, if you delete values in a list, its remaining elements are shifted down by 1 but since the iterator also increments by 1, you miss a value. A trick is to iterate the list in reverse so that any deleted values have already been iterated.
>>> myList = [0,1,2,3,4,5]
>>> mlen = len(myList)
>>> for i, v in enumerate(reversed(myList), 1):
... if v != 3:
... del myList[mlen-i]
...
>>>
>>> myList
But this operation is slow. If you don't need to modify the original list, use a list comprehension
>>> myList = [0,1,2,3,4,5]
>>> myList = [v for v in myList if v==3]
>>> myList
[3]
The issue is you are removing elements from the list you are iterating over. So your loop won't iterate over the entire list.

How to select specific elements in a list and use them (Python)

numbers = [1,2,3,4,5]
How can I pick one element and use it in a calculation?
For example, to pick just the second element on its own. Would it then be possible to store it in another list?
Thanks
You can access and item by its index.
list = ["A","B","C"]
list[0] // returns A
IIUC:
>>> l=[]
>>> numbers=[1,2,3,4,5]
>>> l.append(numbers[1])
>>> l
[2]
>>>
Use append and indexing.
And then, l will have a value which is the second element of numbers.
You can do something like this:
numbers=[1,2,3,4,5]
# Picking up '2' from the list
no = numbers[1] # Since list index starts at 0
print(no) # Prints 2
For storing in another list, you need to declare an empty list where you'll store the value. Like below:
l = []
l.append(no) # Now l contains 2
print(l) # Prints [2]

Extract substrings from a list into a list in Python

I have a Python list like:
['user#gmail.com', 'someone#hotmail.com'...]
And I want to extract only the strings after # into another list directly, such as:
mylist = ['gmail.com', 'hotmail.com'...]
Is it possible? split() doesn't seem to be working with lists.
This is my try:
for x in range(len(mylist)):
mylist[x].split("#",1)[1]
But it didn't give me a list of the output.
You're close, try these small tweaks:
Lists are iterables, which means its easier to use for-loops than you think:
for x in mylist:
#do something
Now, the thing you want to do is 1) split x at '#' and 2) add the result to another list.
#In order to add to another list you need to make another list
newlist = []
for x in mylist:
split_results = x.split('#')
# Now you have a tuple of the results of your split
# add the second item to the new list
newlist.append(split_results[1])
Once you understand that well, you can get fancy and use list comprehension:
newlist = [x.split('#')[1] for x in mylist]
That's my solution with nested for loops:
myl = ['user#gmail.com', 'someone#hotmail.com'...]
results = []
for element in myl:
for x in element:
if x == '#':
x = element.index('#')
results.append(element[x+1:])

Generate one list with multiple elements

I'm trying to generate a list of 100 triangular numbers. This is what I have for generating 100 triangular numbers. When I run it I get 100 lists, how can I change it to generate one list with 100 elements?
def Triangular():
n=0
while n<101:
n=1+n
triangleNumbers = (n*(n+1))//2
print ([triangleNumbers])
Triangular()
Desired Result: [1,3,6,..]
Actual Result:
[1]
[3]
[6]
[10]
[15]
[21]
[28]
...
You need to difine a list , and use the list metohds to help you, code below should solve your problem.
def Triangular():
n=0
result=[]
while n<101:
n=1+n
triangleNumbers = (n*(n+1))//2
result.append(triangleNumbers)
print result
Triangular()
print ([triangleNumbers])
Look at the above statement.
You are creating a new list rather then adding to a list.
>>print (type([triangleNumbers]))
<type 'list'>
Instead,
Initialize an empty list.
append triangleNumbers to the list at every iteration.
Sample code:
lst=[]
def Triangular():
n=0
while n<101:
n=1+n
triangleNumbers = (n*(n+1))//2
lst.append(triangleNumbers)
print lst
Triangular()
To make it more pythonic, you could use a list comprehension
def Triangular(upto):
lst = [(n*(n+1))//2 for n in range(1,upto)]
print lst
Personally I'd make the function return the list only, then let the caller print the result
def Triangular(upto):
return [(n*(n+1))//2 for n in range(1,upto)]
lst = Triangular(101)
print lst
You can do like this too :
lis =[]
for n in range(100):
lis.append((n*(n+1))//2)
print (lis)

Creating an increasing list in Python

I am trying to create some lists from other lists putting some conditions along the way. I want to write these lists finally into a csv. Here is the code which I attempted.
x = [None]*1000
y = [None]*1000
z = [None]*1000
i = 0
for d in range(0,len(productID)):
for j in range(0,len(productID[d])):
if productID[d][j].startswith(u'sku'):
x[i] = map[productID[d][j]]
y[i] = name[d]
z[i] = priceID[d][productID[d][j]].get(u'e')
i = i + 1
plan_name = x[0:i]
dev_name = y[0:i]
dev_price = z[0:i]
This is working fine, but I assume there should be a better way of doing this. Can anyone suggest how can I create a list while looping without having to define it first?
You use .append() to add items to an initially empty list instead.
x, y, z = [], [], []
for d, sublist in enumerate(productID):
for entry in sublist:
if entry.startswith(u'sku'):
x.append(map[entry])
y.append(name[d])
z.append(priceID[d][entry].get(u'e'))
Note that python can loop over sequences directly, and you usually do not need indexes at all. I've used the enumerate() function to add indexes to the outer loop instead (because you seem to need to index into name and priceID there).
.append() adds items to the end of the list:
>>> foo = []
>>> foo.append('bar')
>>> foo.append('spam')
>>> foo
['bar', 'spam']
You may want to read over the Python tutorial; it explains how python lists work nicely.

Categories