I'm currently learning Python, and I struggle to understand what the slicing [:] does in the for loop shown below.  I failed to find any questions about the [:] syntax, so I am posting a question.  I understand that writing namesList[2:] would slice the list from index 2: ['three', 'four', 'five']  And namesList[:2] would slice the list until index 1: ['one', 'two'].    If in the for loop I only put for nm in namesList: it is stuck on an infinite loop, constantly inserting 'four' to index 0. Why is it stuck?  From what I can see in debugging, in the for loop with namesList[:], it continues from where it stopped. But why namesList: doesn't continue, and namesList[:] does? How does [:] work, what does the syntax mean?    names = &quot;one two three four five&quot; namesList = names.split()     for nm in namesList[:]:     if nm[0] == &quot;f&quot;:         namesList.insert(0, nm) print(namesList)  # Output: ['five', 'four', 'one', 'two', 'three', 'four', 'five']   names = &quot;one two three four five&quot; namesList = names.split()     for nm in namesList:     if nm[0] == &quot;f&quot;:         namesList.insert(0, nm) print(namesList)  # Infinite loop
106
I need a good explanation (references are a plus) on Python's slice notation.   To me, this notation needs a bit of picking up.   It looks extremely powerful, but I haven't quite got my head around it.
866
In the following method definitions, what does the * and ** do for param2?  def foo(param1, *param2): def bar(param1, **param2):
10183
Sometimes I like to use a Queueable to perform work on a list of Ids or sObjects over the heaver Batchable Interface.   However, to do this, we need a very solid implementation of an Array slice method.  Most other programming languages have a native slice method, but Apex does not.  While I have written my own version of slice and it's working fine, I would be interested in hearing about other implementations of slice - the more efficient the better.  My version is in this Utilities class on github   It's modelled after the Javascript version described on the mozilla site   I would expect that the usage and output be similar to this:  String[] arr = ['zero', 'one', 'two', 'three']; String[] sliced = Utilities.slice(arr,1, 3);  System.debug(arr);      // ['zero', 'one', 'two', 'three'] System.debug(sliced);   // ['one', 'two']
12905
How do you get the  of two variables in Python?  For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):  str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2):     print "ok" else:     print "bad"   The ^ operator seems to be bitwise, and not defined on all objects:  &gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str'
109666
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?  lst = ['one', 2, 3]  lst1 = list(lst)  lst2 = lst[:]  import copy lst3 = copy.copy(lst)
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
7042
So I can start from len(collection) and end in collection[0].  I also want to be able to access the loop index.
74382
i have:  for i in range(2,n):     if(something):        do something     else:        do something else        i = 2 **restart the loop   But that doesn't seem to work. Is there a way to restart that loop?   Thanks
43330
In python, if I say  print 'h'   I get the letter h and a newline.  If I say   print 'h',   I get the letter h and no newline.  If I say  print 'h', print 'm',   I get the letter h, a space, and the letter m.  How can I prevent Python from printing the space?  The print statements are different iterations of the same loop so I can't just use the + operator.
57185
I want to split a character string n by n. I know how to do that 1 by 1 :  \documentclass{article} \makeatletter  \def\s@plit&lt;#1#2&gt;{%   \ifx\empty#2%     #1%   \else     #1,\s@plit&lt;#2&gt;%   \fi}  \def\Split#1#2{\s@plit&lt;#2\empty&gt;} \makeatother  \begin{document} \Split{1}{123456789} \end{document}   It gives : 1,2,3,4,5,6,7,8,9  But I also want 1,23,45,67,89 or 123,456,789 ... depending from the first parameter.  EDIT  Work straight and reverse, even with foreach.        \documentclass{article}     \usepackage{tikz,xparse,xstring}  \DeclareDocumentCommand{\split}{smmo}{%     \xdef\Entree{#3}%     \let\Sortie\empty%     \IfBooleanTF #1     {% sans étoile         \loop         \StrRight{\Entree}{#2}[\tmp]%         \edef\Sortie{\Sortie,\tmp}%         \StrGobbleRight{\Entree}{#2}[\Entree]%         \unless\ifx\Entree\empty         \repeat         \StrGobbleLeft{\Sortie}{1}[\Sortie]%     }     {% avec étoile dans l'ordre inverse         \loop         \StrRight{\Entree}{#2}[\tmp]%         \edef\Sortie{\tmp,\Sortie}%         \StrGobbleRight{\Entree}{#2}[\Entree]%         \unless\ifx\Entree\empty         \repeat         \StrGobbleRight{\Sortie}{1}[\Sortie]%     }     \IfNoValueTF{#4}{\Sortie}{\edef#4{\Sortie}}     }  \begin{document} \split{2}{6513782}  \split*{2}{6513782}  \split*{2}{6513782}[\bob]  \foreach \x in \bob {[\x] }  \end{document}
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.".
57835
says:  If the index number is @ or *, all members of an array are referenced.  When I do this: LIST=(1 2 3) for i in &quot;${LIST[@]}&quot;; do   echo &quot;example.$i&quot; done  it gives the desired result: example.1 example.2 example.3  But when I use ${LIST[*]}, I get example.1 2 3  instead. Why? Edit: when using printf, @ and * actually do give the same results.
42368
I have a python list, say l  l = [1,5,8]   I want to write a sql query to get the data for all the elements of the list, say  select name from students where id = |IN THE LIST l|   How do I accomplish this?
28573
I want to make an enumerated list in the following format:  [1] foo foo [2] foo foo ...    How I can do that using enumerated lists? I have tried the following:  \begin{enumerate}[\left[ 1 \right]]   but it does not work.
3491
I like TikZ's capability to traverse multiple variables separated by a slash in the foreach (as in the example below). I am looking for something equivalent in PGFplots? I saw in the documentation that say you can't nest the foreach in PGFplots as you can in TikZ, but that only make this kind of feature more important.    Two other small issues:    I like the \x notation so that is why I am using \pgfplotsforeachungrouped. Is there a reason why I should be using pgfplotsinvokeforeach instead?  Also, what is the correct syntax to be able to use a variable to define the list instead of having the actual list in the code. In the following I'd like to be able to reference \ListWithLabels in the foreach.    \documentclass{minimal} \usepackage{pgfplots}  \newcommand*{\ListWithLabels}{-2/a, -1/b, 1/c, 2/d} \newcommand*{\ListWithoutLabels}{-2, -1, 1, 2}  \begin{document} \begin{tikzpicture} \draw [-&gt;][gray, thin](-3,0) -- (3,0) node[blue, right] {$x$};  \draw [-&gt;][gray, thin](0,-3) -- (0,3) node[blue, above] {$y$};  %\foreach \x/\l in \ListWithLabels {  % works \foreach \x/\l in {-2/a, -1/b, 1/c, 2/d} {     \draw [thick, red]         (\x,-2pt) -- (\x,2pt)         node [red, above] {\l}; } \end{tikzpicture}  \begin{tikzpicture} \begin{axis}[     minor tick num=0, axis y line=center, axis x line=middle,      xmin=-3, xmax=3, ymin=-3, ymax=3, xlabel=$x$, ylabel=$y$,     xtick={0},  xticklabels={}     ]  %\pgfplotsinvokeforeach{-2, -1, 1, 2}{             % works %   \addplot [mark=none,color=red, thin, samples=2] %       coordinates{(#1,-0.05) (#1,0.05) }; %}  %\pgfplotsforeachungrouped \x in {\ListWithoutLabels}{  % does not work \pgfplotsforeachungrouped \x in {-2, -1, 1, 2}{    % works     \addplot [mark=none,color=red, thick, samples=2]%         coordinates{ (\x,-0.08) (\x,0.08) }; }   %\pgfplotsforeachungrouped \x/\l in {-2/a, -1/b, 1/c, 2/d}{ % does not work %   \addplot [mark=none,color=red, thin, samples=2]% %       coordinates{ (\x,-0.05) (\x,0.05) } %        node [red, below] {\l}; %}  \end{axis} \end{tikzpicture} \end{document}   Update: I saw  post which explains that the macro in TikZ needs to be not be sourrouned by {}. But that does not work for the PGF commands.  Here is another related post on
410
I needed to create a list of lists in Python, so I typed the following: my_list = [[1] * 4] * 3  The list looked like this: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]    Then I changed one of the innermost values: my_list[0][0] = 5  Now my list looks like this: [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]    which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?
17203
I need to know if a variable in Python is a string or a dict.  Is there anything wrong with the following code?  if type(x) == type(str()):     do_something_with_a_string(x) elif type(x) == type(dict()):     do_somethting_with_a_dict(x) else:     raise ValueError   Update: I accepted avisser's answer (though I will change my mind if someone explains why isinstance is preferred over type(x) is).  But thanks to nakedfanatic for reminding me that it's often cleaner to use a dict (as a case statement) than an if/elif/else series.  Let me elaborate on my use case.  If a variable is a string, I need to put it in a list.  If it's a dict, I need a list of the unique values.  Here's what I came up with:  def value_list(x):     cases = {str: lambda t: [t],              dict: lambda t: list(set(t.values()))}     try:         return cases[type(x)](x)     except KeyError:         return None   If isinstance is preferred, how would you write this value_list() function?