i'm currently learning python3 and my knowledge is basic in the broad scheme of things. I play a lot of computer games but one in particular, if there are enough friends on line we do a custom game between ourselves, so i made a program that randomises the players we have onto teams.  my current code works just fine, but theres a lot of repertivness. I was wondering if there is something i can do in python3 that allows me to splice a list of names in half or half + 1 no matter the amount of names input? so it finds the amount in list, halfs it (or if its odd + 1 to a side) and randomises the names and puts them into either orange or blue team.   Heres the current code:  from random import shuffle players = [''] print("\nA minimum of 6 players is required to use this script") inputPlayers = str(input("Enter player names seperated by a comma: ")) players = inputPlayers.split(", ") shuffle(players)  while len(players) &lt; 6:     print("\nERROR!!! A minimum of 6 players is required to use this script")     inputPlayers = str(input("Enter player names seperated by a comma: "))     players = inputPlayers.split(", ")     shuffle(players)   starts off with importing shuffle, tells the user what to do and input wise and runs a while loop to make sure its done properly, after that comes the repetertiveness, which works just fine, i just dont like it  if len(players)==6:     print('Orange teams is: ')     for i in players[:3]:         print(i)     print()     print('Blue team is: ')     for i in players[3:]:         print(i)   this then carrys on for if len(players)==7: then 8 then 9 then 10! So all in all 40 lines of repeated code. I've tried using start:end but as the list isn't and interger i get an error and my knowledge doesn't cover index method it talks about using.  I know it looks silly to wanna fix something thats not broke, its more im learning and would rather do better code!  any help would be great cheers  Dan
740
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.  I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.  I was looking for something useful in itertools but I couldn't find anything obviously useful. Might've missed it, though.  Related question:
64500
Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this:  class PairEvaluator(HandEvaluator):   def returnArbitrary(self):     return ('ace', 'king')  pe = PairEvaluator() cards = pe.returnArbitrary() print('Two pair, {0}s and {1}s'.format(cards))   When I try to run this code, the compiler gives an IndexError: tuple index out of range. How should I structure my return value to pass it as an argument to .format()?
11919
I have a string ABCCEF and I want to find the number of permutations not counting the duplicates. I ran a piece of python code     len(set([''.join(i) for i in itertools.permutations('ABCCEF')]))   and the output was 360. This piece of code determines all the permutations of ABCCEF (including the duplicates), creates a set of the permutations, then spits out the length of that set.  I am really rusty in the subject of combinatorics but through the magic guess and check, I BELIEVE that the value 360 is determined from  5*4*3*3*2*1 = 360   I determined this from the string have 6 values but only 5 unique values. So on the first slot I have 5 options to choose from, then 4, then 3. then 3 again (2 C's), then 2, then 1.  I dont really have a firm grasp of this concept. I was wondering if anyone could point out flaws in my logic and/or help me with a better process to solve this problem. Pretty much explain to me why I am correct...OR WRONG!
44869
I would like to create some name badges using a loop. I have a spreadsheet with names and affiliations that I save in names.csv file as follows  "Name1","Surname1","Affiliation1", "Name2","Surname2","Affiliation2", "Name3","Surname3","Affiliation3"   I can copy the content of names.csv in a string array and use a loop to recover the entries. The following is an example of working code producing the output Surname2:    \documentclass{article} \usepackage{tikz} \usepackage{pgf} \usepackage{array}  \def\names{{"Name1","Surname1","Affiliation1", "Name2","Surname2","Affiliation2", "Name3","Surname3","Affiliation3"}}  \begin{document}  \pgfmathparse{\names[4]}\pgfmathresult  \end{document}   I can use this idea to create hundreds of name badges in a loop. But instead of writing the whole list in the .tex file I would like to call directly my names.csv file. I used the modified code  \documentclass{article} \usepackage{tikz} \usepackage{pgf} \usepackage{array}  \def\names{{\input{names.csv}}}  \begin{document}  \pgfmathparse{\names[4]}\pgfmathresult  \end{document}   which apparently enters in an endless loop. I understood that \input{} works just as copy-pastying, but it doesn't seem the case. Of course I can work in the spreadsheet and then copy paste the names.csv file content, but I would like to understand what happens. Any clues?  PS edit: The suggested solution is enough for my case. But still I would like to be able to define macros with \input'. It seems that\input{}' inside a macro is not expanded immediately. I mean if I have some code in file.tex', that I want to plugin in a new macro,\def\mymacro{\input{file}}' will save \mymacro' as '\input{file}' and will only look what's inside the file when I call the macro in the document. That's why in the previous example\names' is not understood as an array. In the same way  \begin{filecontent*}{newfile.tex} \input{file} \end{filecontent*}   will save the code \input{file}' innewfile.tex', but not the content in `file.tex'. Anyone has any idea how to force input to expand?
8585
Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:  def uniq(input):   output = []   for x in input:     if x not in output:       output.append(x)   return output   (Thanks to  for that .)  But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.  Related question:
108260
So I have been tasked to make an array without duplicated values from another existing array. So I did it, but I want to know is there some other better way to do that. Example input/output: Input: 10, 15, 10, 5, 1, 3 Output: 10, 15, 5, 1, 3 So here is my code. #include &lt;stdio.h&gt;  int main(void) {   const int MAX_ARRAY_SIZE = 5;    int m[MAX_ARRAY_SIZE], p[MAX_ARRAY_SIZE];     for(int i = 0; i &lt; MAX_ARRAY_SIZE; i++) {     printf(&quot;Enter number: &quot;);     scanf(&quot;%d&quot;,&amp;m[i]);   }   int k = 0;   int dup = 0;   for(int i =0; i &lt; MAX_ARRAY_SIZE; i++) {     for(int j = i +1; j &lt;MAX_ARRAY_SIZE; j++) {         if(m[i] == m[j]) {             dup = 1;         }     }     if(dup != 1) {       p[k++] = m[i];     }     dup = 0;   }    printf(&quot;The new array without repeated values\n&quot;);   for(int i = 0; i &lt; k; i++) {     printf(&quot;%d\n&quot;,p[i]);   }    return 0; }  I'm not sure if this is the right and simple way I do that. I want some suggestions. Thanks in advance. :)
16336
Given the following code (that doesn't work):  while True:     #snip: print out current state     while True:         ok = get_input("Is this ok? (y/n)")         if ok.lower() == "y": break 2 #this doesn't work :(         if ok.lower() == "n": break     #do more processing with menus and stuff   Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?
2695
Some of you may recognize this as Project Euler's problem number 11. The one with the grid.  I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why  grid = [  [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ], ...   And I get this error:     File "D:\development\Python\ProjectEuler\p11.py", line 3     [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ],        ^ SyntaxError: invalid token   Why is it throwing an error before the comma?
112773
I need to be able to take a string like:  '''foo, bar, "one, two", three four'''   into:  ['foo', 'bar', 'one, two', 'three four']   I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
52669
Does anyone know how to use the .upper() in a stand alone python script so it can be used to change all characters in a table into UPPER case?  I don't want to use the field calculator since I have multiple tables, etc...  I currently am using a cursor to correct mistakes in my tables, but can't figure out the correct syntax to use it to convert all the strings to UPPER case!    The above question would apply equally well when the change of case desired is to lower or title.
2785
I have a list of integers that I would like to convert to one number like:  numList = [1, 2, 3] num = magic(numList)  print num, type(num) &gt;&gt;&gt; 123, &lt;type 'int'&gt;   What is the best way to implement the magic function?  EDIT  I did find , but it seems like there has to be a better way.
68354
Is there anyway to get tuple operations in Python to work like this:  &gt;&gt;&gt; a = (1,2,3) &gt;&gt;&gt; b = (3,2,1) &gt;&gt;&gt; a + b (4,4,4)   instead of:  &gt;&gt;&gt; a = (1,2,3) &gt;&gt;&gt; b = (3,2,1) &gt;&gt;&gt; a + b (1,2,3,3,2,1)   I know it works like that because the __add__ and __mul__ methods are defined to work like that. So the only way would be to redefine them?
34869
How can I iterate, loop, process, or otherwise do something, with each element from a comma separated list of things?  This question       , and the are already lots of very good answers everywhere. However I think it would also be valuable to have a single reference point where all such alternative techniques are explained in detail, with their advantages and disadvantages discussed.  All of plain-TeX, LaTeX, LaTeX3, LuaTeX, Context, etoolbox, pgffor, etc. answers are invited. Please consider explaining, for example:   How does the command/method deal with whitespace around items? How does the command/method deal with empty/missing items? (e.g. a,b,,c) How does the command/method deal with a trailing comma? Can the command/method work of a list stored on a macro? Is each iteration evaluated globally or on a local group? (i.e., if a command is defined during an iteration, does the command survive the loop?) Do items get expanded or somehow mangled before being processed? What about lists where items are key=value or some other kind of pairs? Does the method work for lists separated with something other than a comma? Any other thing I should know before deciding to use this method?
116007
In , is the following the only way to get the number of elements?  arr.__len__()   If so, why the strange syntax?
8317
If I have sequence of sequences (maybe a list of tuples) I can use itertools.chain() to flatten it. But sometimes I feel like I would rather write it as a comprehension. I just can't figure out how to do it. Here's a very construed case:  Let's say I want to swap the elements of every pair in a sequence. I use a string as a sequence here:  &gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; seq = '012345' &gt;&gt;&gt; swapped_pairs = zip(seq[1::2], seq[::2]) &gt;&gt;&gt; swapped_pairs [('1', '0'), ('3', '2'), ('5', '4')] &gt;&gt;&gt; "".join(chain(*swapped_pairs)) '103254'   I use zip on the even and odd slices of the sequence to swap the pairs. But I end up with a list of tuples that now need to be flattened. So I use chain(). Is there a way I could express it with a comprehension instead?  If you want to post your own solution to the basic problem of swapping elements of the pairs, go ahead, I'll up-vote anything that teaches me something new. But I will only mark as accepted an answer that is targeted on my question, even if the answer is "No, you can't.".
94174
When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad.  For example, you can't do this:  for name in names:     if name[-5:] == 'Smith':         names.remove(name)   I usually end up doing something like this:  toremove = [] for name in names:     if name[-5:] == 'Smith':         toremove.append(name) for name in toremove:     names.remove(name) del toremove   This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one?   How about one that works with dictionaries?
6976
What's the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It's OK to mutate the original List, so no copying should be necessary. The method signature could be  /** Split a list into two sublists. The original list will be modified to  * have size i and will contain exactly the same elements at indices 0   * through i-1 as it had originally; the returned list will have size   * len-i (where len is the size of the original list before the call)   * and will have the same elements at indices 0 through len-(i+1) as   * the original list had at indices i through len-1.  */ &lt;T&gt; List&lt;T&gt; split(List&lt;T&gt; list, int i);   [EDIT] List.subList returns a view on the original list, which becomes invalid if the original is modified. So split can't use subList unless it also dispenses with the original reference (or, as in Marc Novakowski's answer, uses subList but immediately copies the result).