Suppose I have a list
list1 = ["hola", "como", "estas", "vos?", "chau"]
I want to put in another list let's say list2
all the elements of the list1
iterating two by two. In other words, in that example I was left with:
list2 = ["como", "vos?"]
The question is very simple but it doesn't come out... I wanted to do the following but as you can see there I print the numbers and not the strings of the list:
Wrong code:
max = len(list1).split(" ")
for x in range(0,max,2):
lista2.append(x)
@AND. Betanzos correctly explains what you are doing wrong in your code in his answer. However, you can do what you want more simply and efficiently using list slicing:
The general syntax is
[inicio:final:paso]
. In[1::2]
, the 1 indicates to cut the list from the second element (index 1), the 2 indicates to take every other element. If the initial index is not specified, it is taken from the first element, if the final index is not specified, it is taken until the last element and if the step is not specified, the elements are taken one by one. The above is therefore equivalent tolist1[1:len(list1):2]
Several things to note:
1 - What are you trying to do with:
The function
len()
allows you to know the length of the list, so it returns a number and you apply a to that numbersplit()
as ifString
it were a. This should throw you an error like this:What you need to do is simply save the result of the call to
len()
the variablemax
.2 - In list2 you put
x
instead of the element of list1What the loop
for
does, as you define it, is to generate a number between 0 (inclusive) and the value that the variable hasmax
(exclusive) that we assume is effectively the length of the listlist1
, all this with a jump between a generated value and the next of 2.So far so good, but if you want to start from the element
"como"
instead of 0 you have to put 1, since this is the position where the element is located. Then you take the element oflist1
at the positionx
generated by the range and that's what you put intolista2
.Everything would be like this: