Lists, how to add multiple values at one time - python

i just wondered if there is a way to append at one time multiple values i.e.
defining an function with the parameter x, that will automaticly append the amount of elements definied by an x.
def Append(x):
L = []
L.append(x - Elements)
return L
Thanks in advance

Try this to append several similar values to an existing list:
>>> l = [1,2]
>>> l += [3]*2
>>> l
[1, 2, 3, 3]
.extend() list method works too
>>> l = [1,2]
>>> l.extend([3]*2)
>>> l
[1, 2, 3, 3]

i meant it to add an x-Amount of Elements, not an specific one but just for example: Append(20) -> Should add 20 new elements

Related

How to iterate the first index value twice before going to the next index position?

I'm trying to make a for loop that iterates each index twice before going to the next one, for example if I have the following list:
l = [1,2,3]
I would like to iterate it if it was in this way:
l = [1,1,2,2,3,3]
could someone help me with this problem please?
The most obvious thing would be a generator function that yields each item in the iterable twice:
def twice(arr):
for val in arr:
yield val
yield val
for x in twice([1, 2, 3]):
print(x)
If you need a list, then
l = list(twice([1, 2, 3]))
You could make a list comprehension that repeats the elements and flattens the result:
l = [1,2,3]
repeat = 2
[n for i in l for n in [i]*repeat]
# [1, 1, 2, 2, 3, 3]
You can solve this by using NumPy.
import numpy as np
l = np.repeat([1,2,3],2)
Repeat repeats elements of an array the specified number of times. This also returns a NumPy array. This can be converted back to a list if you wish with list(l). However, NumPy arrays act similar to lists so most of the time you don't need to change anything.
Unsurprisingly, more-itertools has that:
>>> from more_itertools import repeat_each
>>> for x in repeat_each([1, 2, 3]):
... print(x)
...
1
1
2
2
3
3
(It also has an optional second parameter for telling it how often to repeat each. For example repeat_each([1, 2, 3], 5). Default is 2.)
l = [1, 2, 3]
lst = []
for x in l:
for i in range(2):
lst.append(x)
print(lst)
# [1, 1, 2, 2, 3, 3]

How to use sequence unpacking with a sequence of variable length?

If I know the length of a list in advance, I can use sequence unpacking to assign variable the elements of the list thus:
my_list = [1,2,3]
x, y, z = my_list
If I don't know the length of the list in advance, how can I assign variables to the elements of the list using sequence unpacking? If for argument's sake I don't care how the variables are named, can I first get the length of the list and then unpack to this amount of arbitrarily-named variables?
Certainly not recommend but possible:
my_list = [1, 2, 3]
for counter, value in enumerate(my_list):
exec 'a{} = {}'.format(counter, value)
print a0, a1, a2
Output:
1 2 3
Or use Python 3:
>>> a, *rest = my_list
>>> a
1
>>> rest
[2, 3]
you can force the length of the list to unpacking to the size you want like this
>>> my_list=range(10)
>>> a,b,c = my_list[:3]
>>> a
0
>>> b
1
>>> c
2
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
if they are less you get a error, otherwise you take the 3 first elements
to the case of less elements you can do something like this
>>> my_list=[1,2]
>>> x,y,z=(my_list[:3] +[-1]*3)[:3]
>>> x
1
>>> y
2
>>> z
-1
>>>
have a list with default values that you concatenate to the sub-list of my_list and from the result you take what you need
The right answer is that you should leave these elements in a list. This is what a list is for.
The wrong answer is to add local variables in a roundabout way. For Python 3:
ctr = 0
for value in my_list:
__builtins__.locals()['my_list_{}'.format(ctr)] = value
ctr += 1
If my_list has n items, this will create variables my_list_0, my_list_1, ..., my_list_{n-1}.
Please don't do this.

remove non repeating characters from a list

I am trying to remove non repeating characters from a list in python. e.g list = [1,1,2,3,3,3,5,6] should return [1,1,3,3].
My initial attempt was:
def tester(data):
for x in data:
if data.count(x) == 1:
data.remove(x)
return data
This will work for some inputs, but for [1,2,3,4,5], for example, it returns [2,4]. Could someone please explain why this occurs?
l=[1,1,2,3,3,3,5,6]
[x for x in l if l.count(x) > 1]
[1, 1, 3, 3, 3]
Adds elements that appear at least twice in your list.
In your own code you need to change the line for x in data to for x in data[:]:
Using data[:] you are iterating over a copy of original list.
There is a linear time solution for that:
def tester(data):
cnt = {}
for e in data:
cnt[e] = cnt.get(e, 0) + 1
return [x for x in data if cnt[x] > 1]
This is occurring because you are removing from a list as you're iterating through it. Instead, consider appending to a new list.
You could also use collections.Counter, if you're using 2.7 or greater:
[a for a, b in collections.Counter(your_list).items() if b > 1]
Another linear solution.
>>> data = [1, 1, 2, 3, 3, 3, 5, 6]
>>> D = dict.fromkeys(data, 0)
>>> for item in data:
... D[item] += 1
...
>>> [item for item in data if D[item] > 1]
[1, 1, 3, 3, 3]
You shouldn't remove items from a mutable list while iterating over that same list. The interpreter doesn't have any way to keep track of where it is in the list while you're doing this.
See this question for another example of the same problem, with many suggested alternative approaches.
you can use the list comprehention,just like this:
def tester(data):
return [x for x in data if data.count(x) != 1]
it is not recommended to remove item when iterating

Manipulating Python Lists

I have a list of 100 elements. I am trying to create a function that will make 300 copies of that list and then store those copies into a blank list. I then need the function to choose an indexed value at random from each copied list. So, it might choose the 25th index value in the first copied list, and then it might choose the 60th index value in the next copied list. Then, the index of the value is an argument of a pre-defined function. The problem is that my copied lists are not being manipulated.
my code is as follows:
def condition_manipulate(value):
list_set=[] #this is the list in which the copied lists will go
for i in range(0,value):
new_list=initial_conditions[:] #initial_conditions is the list to be copied
list_set.append(new_list)
for i in list_set: #My confusion is here. I need the function to choose
for j in i: #A random value in each copied list that resides
x=random.choice(i) #In list_set and then run a predefined function on it.
variable=new_sum(i.index(x)
i[i.index(x)]=variable
return list_set
#running condition_manipulate(300) should give me a list with 300 copies of a list
#Where a random value in each list is manipulated by the function new_sum
I have tried almost everything. What am I doing wrong? Any Help will be appreciated. Thanks.
Try:
import random
def condition_manipulate(value):
list_set=[]
for i in range(value):
new_list=initial_conditions[:]
i=random.choice(range(len(initial_conditions)))
new_list[i]=new_sum(new_list[i])
list_set.append(new_list)
return list_set
If you really need copies of lists rather than shallow copies then you need to:
import copy
oldlist = [.....]
newlist = copy.deepcopy(oldlist)
Otherwise all the copies are really the same list.>>> o = [1, 2, 3]
>>> n = o
>>> n.append(4)
>>> o
[1, 2, 3, 4]
>>> n = copy.deepcopy(o)
>>> n
[1, 2, 3, 4]
>>> n.append(5)
>>> n
[1, 2, 3, 4, 5]
>>> o
[1, 2, 3, 4]
>>>

Python: identical items in list are treated as the same

I have a nested list in python. Each item the second list is also a nested list. My goal is to duplicate one list, insert it right at the same index, and then modify each one. So, example of start condition:
myList = [[first_list], [[element_1], [element_2, element_3], [duplicate_me]]]
Duplication/insertion at myList[1][2]:
myList = [[first_list], [[element_1], [element_2, element_3], [duplicate_me], [duplicate_me]]]
This all works fine. However, when I run the append code:
myList[1][2].append(new_element)
It appends the new element to both duplicates, like this:
myList = [[first_list], [[element_1], [element_2, element_3], [duplicate_me, new_element], [duplicate_me, new_element]]]
Is there something bizarre going on in the way the elements are called or indexed? I see a potential workaround (calling the item to be duplicated to a working variable, modifying it there, and then inserting it at the same point), but that seems needlessly complex.
Thanks!
myList[1][2] and myList[1][3] don't just have the same values, they are actually the same list. You are looking at the same area in memory when you read both of them. So, when you change one, you are changing the other, because both are actually the exact same thing! Instead doing what you do to duplicate the list, you should make a copy of it.
Here's an example of the problem from a python shell:
>>> mylist = [1, 2, 3]
>>> newlist = mylist
>>> newlist.append(4)
>>> newlist
[1, 2, 3, 4]
>>> mylist
[1, 2, 3, 4]
A common way to fix this is to use one of these tricks:
>>> mylist = [1, 2, 3]
>>> newlist = mylist[:] # OR :
>>> newlist = [x for x in mylist]
>>> newlist.append(4)
>>> newlist
[1, 2, 3, 4]
>>> mylist
[1, 2, 3]
The second and third lines will create a copy of the list. I tend to combine the two like this, if I need to copy a 2D list:
>>> newlist = [x[:] for x in mylist]
Use one of these to create your duplicate, and all will be well again.
You are most likely not duplicating the target list (*[duplicate_me]*), but rather simply appending a duplicated reference to the same list into myList.
You need to copy the list before adding it to myList. One simple way is to call the list constructor passing in the original [duplicate_me]

Categories