-6

ok looks like many did not understand the question. i will make it more clear.

i got a list:

List_1 = [1,2,3,4,5,6,7,8,9]

and what i do in my program is that if i press 1 that will make List_1[0] into X or what ever number i press, it turns it into an X. my list has 9 numbers total.

What i want to do, is that IF 3 specific numbers are converted into X then the program will move on.

so if i end up with:

List_1 = [1,'X',3,4,'X',6,'X',8,9]

then the program will move on.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

3

If you need a contiguous set (such as the first three entries in your original question) use slice syntax:

list_2 = a[:3]

If you need only those elements from a specific set, use a comprehension:

stuff_i_need = [1, 'gg']
list_2 = [x for x in L if x in stuff_i_need]

(although, if you know what you need and it is a very small list, then just manually accessing the locations in the list that contain the elements you need is fine).

If you want to make a string of some contents of the list, one option is to just concatenate them yourself and wrap the elements with the string constructor str:

str(L[0]) + str(L[3])

Another way to do the same thing is:

import operator
reduce(operator.add, map(str, L))

# Also, just replace L with any of the slicing or accessing mentioned above.
ely
  • 74,674
  • 34
  • 147
  • 228
  • If you want [1,3,5] then just access the locations for those elements. list2 = List[0:1] + List[2:3] + List[4:5]. The text above game me the answer, but i wonder why is it List[0:1] and [2:3] and not just List[0] + List[3]? what dose the "2:3" mean? – user2911693 Oct 23 '13 at 14:50
1

Use a slice, as mentioned the other answers and comments. But if the indices are non-contiguous you can use a list comprehension together with enumerate:

>>> [x for i, x in enumerate(a) if i in [0, 1, 3]]
[1, 'X', 'X']

Update

The question changed, asking instead how to take different parts of a list and join them into a string. A small modification of the above:

>>> "".join(str(x) for i, x in enumerate(L) if i in [0, 3])
'1gg'