This question already has answers here:
Understanding slicing
(38 answers)
Closed 8 years ago.
Suppose I have a list [1,2,3,4,5]. Now I want to pass the elements of this list, starting from 3rd element to a method.
i.e. i want to invoke:
myfunction([3,4,5])
How can I do this in python. tried passing mylist[2], but it doesn't quite work this way it seems.
slicing.
mylist = range(1,6)
>> [1,2,3,4,5]
myfunction(mylist[2:])
>> [3,4,5]
Related
This question already has answers here:
Apply function to each element of a list
(4 answers)
Python Splitting Array of Strings
(6 answers)
Split each string in list and store in multiple arrays
(4 answers)
Closed 1 year ago.
I have a list
list = ['a:b:c:d', 'e:f:g:h', 'i:j:k:l']
What I'm trying to do is make a list of each of it's elements. Something like this:
listelement[0] = list[0].split(':')
print(listelement[0][1])
output: b
I can't seem to figure out how to create something that works similarly to this.
You can try list comprehension to do what you want.
new_list = [element.split(':') for element in list].
Also I would advise against the use of list as a name, since it's a reserved word.
This question already has answers here:
Understanding slicing
(38 answers)
Closed 2 years ago.
I have a list in python, eg. [1,2,3,4,5,6,7,8,9,10,11,12]
I want to make a new list with only the 4. element from the right? .. how to do that, eg. with a one liner.
eq. to .. [4,8,12]
You can do it simply like so in one line: (where a is your list)
print(a[-1::-4][::-1])
foo = [1,2,3,4,5,6,7,8,9,10,11,12]
print(foo[-1::-4])
output
[12, 8, 4]
reverse it, if the order is important
This question already has answers here:
Pythonic way to return list of every nth item in a larger list
(9 answers)
Closed 4 years ago.
I have a list
list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
I need to store every fifth element, with the result:
result=[5,10,15]
list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
results = list[4::5]
Here you go!
This question already has answers here:
Python list confusion [duplicate]
(3 answers)
Closed 8 years ago.
I want to change only one element in the 2d list. I can change an element in list1 using list1[0][2] = "x" but when i do the same for list2 more than one element is changed.
list1 = []
for i in range(0,5):
list1.append(['O']*5)
list2 = [['o','o','o','o','o']]*5
Because this is 5 copies of the same list
list2 = [['o','o','o','o','o']]*5
Getting a good understanding of when it's ok to use copies of the same reference, and when it's not ok is important to writing efficient code.
This question already has answers here:
Create a list with initial capacity in Python
(11 answers)
Closed 9 years ago.
I want to do the following :
l = list()
l[2] = 'two'
As expected, that does not work. It returns an out of range exception.
Is there any way to, let say, define a list with a length ?
Try this one
values = [None]*1000
In place of 1000 use your desired number.